这是我的桌子
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出现在这2列中的任何一列中
我用这个查询
SELECT `SenderID` FROM `messages` WHERE `RecieverID` = 2
UNION
SELECT `ReceiverID` FROM `messages` WHERE `SenderID` = 2
提供唯一的答案,但顺序错误
像这样
ReceiverID
7
6
5
我希望此查询的答案按ID DESC排序,在该ID中,发生特定的发送者或接收者ID,例如,在我的表中,发送者2和reverid 7之间的味精在ID 5处,而最新ID btweend sendr2和6之间的味精在id 3和btweed sndr2和5是ID 7 sot上面的答案应按以下顺序排序:5、7、6而不是7,6,5
最佳答案
此人将通过他们最近的对话来排序发送者/接收者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