结果从MySQL查询返回两次

时间:2017-07-20 09:12:06

标签: mysql sql

我正在努力弄清楚为什么我的结果会为群组消息返回两次。它会为单个会话返回正确的值。

它应该从Data in table屏幕截图返回所有数据。但是,它会使用is_group = 1两次返回数据。

表格中的数据:

enter image description here

MySQL查询:

(SELECT dm.* FROM `direct_message`AS dm 
 INNER JOIN direct_message_thread AS dmt    
 ON dmt.chat_id = dm.id 
 WHERE 
 ( dm.recipient_id = '10896' OR dm.creator_id = '10896' ) 
 AND dm.school_id = '1' 
 GROUP BY dm.id 
 ORDER BY dmt.inserted DESC 
) UNION ALL ( 
    SELECT dm.* FROM `direct_message` AS dm 
    INNER JOIN direct_message_thread AS dmt ON dmt.chat_id = dm.id 
    LEFT JOIN direct_message_group AS dmg ON dmg.chat_id = dm.id 
    WHERE dmg.staff_id = '10896' AND dm.school_id = '1' 
    GROUP BY dm.id 
    ORDER BY dmt.inserted DESC
) LIMIT 0, 25

结果:

enter image description here

我认为可能是因为第一个SELECT得到了结果,然后UNION ALL获得了相同的结果,但没有与第一个SELECT

组合在一起

当我尝试执行以下操作时:

(SELECT dm.* FROM `direct_message`AS dm 
 INNER JOIN direct_message_thread AS dmt    
 ON dmt.chat_id = dm.id 
 WHERE ( dm.recipient_id = '10896' OR dm.creator_id = '10896' ) 
 AND dm.school_id = '1' 
) UNION ALL ( 
    SELECT dm.* FROM `direct_message` AS dm 
    INNER JOIN direct_message_thread AS dmt ON dmt.chat_id = dm.id 
    LEFT JOIN direct_message_group AS dmg ON dmg.chat_id = dm.id 
    WHERE dmg.staff_id = '10896' AND dm.school_id = '1' 
) 
GROUP BY dm.id 
ORDER BY dmt.inserted DESC
LIMIT 0, 25

显示以下错误消息:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法   靠近' GROUP BY dm.id ORDER BY dmt.inserted DESC LIMIT 0,25'在线   14

1 个答案:

答案 0 :(得分:0)

您正在使用union进行两次查询。 记录595-597和599-601都符合它们。

我最好选择使用

进行整个查询
select id,...
    from (...)
group by id