对2个不同列的Union结果使用Order By和Group by

时间:2016-08-24 20:25:43

标签: mysql select group-by sql-order-by union

这是我的表

ID      Value           SenderID     RecieverID
1       Hello There         2           7
2       etc etc             7           5
3       etc                 2           6
4       ee                  7           2
5       asdas               2           7
6       asdas               2           5
7       asdas               7           5

我想要的是来自所有行的senderID或receiverID中的值,其中特定值假设为2出现在这两列中的任何一列中 我用过这个查询

SELECT `SenderID` FROM `messages` WHERE `RecieverID` = 2
UNION
SELECT `ReceiverID` FROM `messages` WHERE `SenderID` = 2 

给出了独特的答案,但顺序错误 像这样

ReceiverID
7
6
5

我期待这个查询的答案由ID DESC排序,其中特定的发送者或接收者ID在我的表中发生,例如在senderid 2和reverid 7之间的msg是id 5,最新的id是btweend sendr2和6是在id 3和btweed sndr2和5它是ID 7 sot上面的答案应该按照这样的5,7,6而不是7,6,5进行排序

3 个答案:

答案 0 :(得分:1)

您需要在括号中使用内部查询以设置顺序所指的内容:

SELECT id, senderID from 
  (SELECT ID, `SenderID` FROM `messages` WHERE `RecieverID` = 2
   UNION
   SELECT ID, `RecieverID` as senderId FROM `messages` WHERE `SenderID` = 2
  ) as A
GROUP BY (SenderID)
order by ID ASC

答案 1 :(得分:1)

这个会根据最近的对话订购发件人/收件人ID:

SELECT senderID -- , MAX(ID) as maxID -- uncomment to see maxID
FROM (
  SELECT ID, `SenderID` FROM `messages` WHERE `RecieverID` = 2
  UNION ALL
  SELECT ID, `RecieverID` FROM `messages` WHERE `SenderID` = 2
) as sub
GROUP BY (SenderID)
ORDER BY MAX(ID) DESC

http://sqlfiddle.com/#!9/6d7bc0/1

答案 2 :(得分:0)

SELECT ID, IF(`SenderID` = 2,`RecieverID`,`SenderID`)
  FROM `messages`
 WHERE `RecieverID` = 2 OR `SenderID` = 2
 group by IF(`SenderID` = 2,`RecieverID`,`SenderID`)
 order by ID ASC