我有一个名为'items'的表
id sender receiver item
1 1 2 computer
2 2 1 mobile
3 1 3 ipad
4 4 1 ring
5 3 1 camera
6 1 8 pc
7 5 1 ring
8 1 10 tablet
以下查询,如
SELECT receiver id FROM items WHERE sender ='1'
UNION
SELECT sender FROM items WHERE receiver ='1'
ORDER BY 1 DESC
发出订单
10
8
5
4
3
2
如果我想获得发送者/接收者的订单,发送者/接收者的最后一次互动发生在哪里发送者/接收者= 1,我指的是订单(10,5,8,3,4,2)。
在第8行中,user = 1的对手是10
在第7行中,user = 1的对手是5
在第6行,user = 1的对手是8
在第5和第3行,对手用户= 1,是3
在第4行中,user = 1的对手是4
在第1&第二行,用户= 1的对手是2
答案 0 :(得分:1)
尝试这种方式:
SELECT distinct receiver FROM (
SELECT receiver, id FROM items WHERE sender ='1'
UNION
SELECT sender, id FROM items WHERE receiver ='1'
ORDER BY id DESC) sortedtable
10
5
8
3
4
2
答案 1 :(得分:0)
或使用分组依据:
SELECT t.user, max(t.id)
FROM
(
SELECT receiver as user, id FROM items WHERE sender ='1'
UNION
SELECT sender as user, id FROM items WHERE receiver ='1'
) as t
GROUP BY t.user
ORDER BY max(t.id) DESC
http://sqlfiddle.com/#!2/5e971/1/0
没有UNION的另一个选项:
SELECT
CASE receiver
WHEN '1' THEN sender
ELSE receiver
END as user,
max(id)
FROM items WHERE sender ='1' OR receiver ='1'
GROUP BY user
ORDER BY max(id) DESC