带有连接和多个组的SQL查询

时间:2016-06-19 09:16:53

标签: mysql sql postgresql join group-by

我有表消息:

enter image description here

我想重新开始谈话。对话是指id_sender和id_recipient和id_ad在行中相同。但是例如:

第一行:id_sender = 1 id_recipient = 2 id_ad = 1

第二行id_sender = 2 id_recipient = 1 id_ad = 1

这两行应该分组到一个对话,所以我创建了查询:

SELECT id_ad
     , id_sender
     , u.name
     , id_recipient
     , uu.name
     , subject from ads.messages m
  JOIN ads.advertisements 
 USING (id_ad)
  JOIN ads.users u 
    ON m.id_sender = u.id_user
  JOIN ads.users uu 
    ON m.id_recipient = uu.id_user
 WHERE m.id_recipient = 133 
    OR m.id_sender = 133
 GROUP 
    BY id_ad
     , id_sender
     , subject
     , u.name
     , m.id_recipient
     , uu.name

返回:

enter image description here

这个查询是正确的但我需要在上面的图像上返回一个结果,查询应返回3行

哪一个将返回无关紧要 - 要重新运行我需要所有这一列和结果行应该是3而不是4

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我必须编辑一些你的代码,但结果再次与上面相同:

enter image description here