我有一张这样的桌子。
| id-AI | from | to | text |created_date
+----+---------+-------+-------------+-------------
| 1 | 7 | 1 | from 7 to 1 |2015-11-06 04:59:14
| 2 | 1 | 2 | from 1 to 2 |2015-11-06 04:57:06
| 3 | 7 | 1 | from 7 to 1 |2015-11-06 04:25:45
| 4 | 1 | 6 | from 1 to 6 |2015-11-06 04:25:32
| 5 | 1 | 5 | from 1 to 5 |2015-11-06 04:25:16
我想要一个这样的列表。一个用户列表敲我或我敲他/她或我们进行了长时间的对话。我想要的列表应该是最新的顺序,就像facebook消息一样。
| users |
+-------+
| 7
| 2
| 6
| 5
1是主user_id。获取列表,其中涉及1(在或从中)然后这称为对话。
答案 0 :(得分:2)
您可以使用以下查询:
SELECT IF (`from` = 1, `to`, `from`)
FROM mytable
WHERE 1 IN (`from`, `to`)
ORDER BY created_date DESC
这将返回每个对话的创建者或收件人,其中涉及user_id = 1
。
获取有序的不同 user_id
值集合使用此查询:
SELECT IF (`from` = 1, `to`, `from`)
FROM mytable
WHERE 1 IN (`from`, `to`)
GROUP BY IF (`from` = 1, `to`, `from`)
ORDER BY MAX(created_date) DESC
答案 1 :(得分:0)
使用UNION:
SELECT user
FROM (SELECT to AS user, created_date
FROM mytable
WHERE from = 1)
UNION
SELECT from AS user, created_date
FROM mytable
WHERE to = 1) x
GROUP BY user
ORDER BY MAX(created_date) DESC