【问题标题】:php mysql I tray to join 3 table but in show duplicated resultphp mysql我尝试加入3个表但显示重复结果
【发布时间】:2020-11-25 01:13:10
【问题描述】:

我有 3 个表格

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   

我想显示所有与 group_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;
}

【问题讨论】:

标签: php mysql sql join


【解决方案1】:

需要修复引入表groups的join条件。

你有:

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 = ?

【讨论】:

  • 非常感谢我使用(在 group_not.group_id = groups.group_id 上加入群组)及其工作
【解决方案2】:

我建议您使用 SELECT DISTINCT AS BELOW:

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";

SELECT DISTINCT 语句用于仅返回不同(不同)的值。

【讨论】:

    猜你喜欢
    • 2021-04-03
    • 2019-04-18
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多