php mysql i托盘连接3表但在显示重复的结果

wbgh16ku  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(249)

我有三个标签 notifications ```
not_id | not_name

2 | Notification Name 01
3 | Notification Name 02
4 | Notification Name 03
`groups`
group_id | group_name

4 | group name 1
5 | group name 2
`group_not`

group_not_id | group_id | not_id

 1       |     4     |      2   
 2       |     4     |      3   
 3       |     5     |      4
我要显示与组id为4的组相关的所有通知
但php端显示如下:

Notification Name

Notification Name 01
Notification Name 01
Notification Name 02
Notification Name 02

mysql代码

function getRows_not_group($group_id)
{
global $conn;
$sql = "SELECT group_not.group_not_id, notifications.not_name, groups.group_name FROM group_not JOIN groups ON group_not.group_id = $group_id JOIN notifications ON group_not.not_id = notifications.not_id WHERE group_not.group_id = $group_id";
$result = mysqli_query($conn, $sql);
if(!$result)
{
echo mysqli_error($conn);
}
$rows = [];
if(mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$rows[] = $row;
}
}
return $rows;
}

1l5u6lss

1l5u6lss1#

引入表的连接条件 groups 需要修复。
您有:

SELECT ...
FROM group_not 
JOIN groups ON group_not.group_id = $group_id   --> here
JOIN notifications ON group_not.not_id = notifications.not_id 
WHERE group_not.group_id = $group_id

当你真的需要:

JOIN groups ON group_not.group_id = groups.group_id

我还建议使用表别名使查询更易于读写。您还应该使用参数化查询,而不是在查询字符串中串联变量。所以:

SELECT gn.group_not_id, n.not_name, g.group_name 
FROM group_not gn 
INNER JOIN groups g ON gn.group_id = g.group_id
JOIN notifications ON gn.not_id = n.not_id 
WHERE gn.group_id = ?
edqdpe6u

edqdpe6u2#

我建议您使用select distinct,如下所示:

SELECT DISTINCT group_not.group_not_id, notifications.not_name, groups.group_name FROM group_not JOIN groups ON group_not.group_id = $group_id JOIN notifications ON group_not.not_id = notifications.not_id WHERE group_not.group_id = $group_id";

SELECTDISTINCT语句仅用于返回不同的值。

相关问题