我只想显示我发送消息或接收消息的朋友列表,按最后一次发送消息的时间(由朋友或我)排序。
尝试这个:
SELECT DISTINCT friends.id
FROM messages m
INNER JOIN
(
SELECT uid id FROM friends WHERE status = 1 AND fid = myuserid
UNION ALL
SELECT fid FROM friends WHERE status = 1 AND uid = myuserid
) friends ON m.fid = friends.id OR m.uid = friends.id
但是,如果有一个users
表,你可以这样做:
SELECT
senders.name 'From',
recievers.name 'To',
m.id,
m.body,
m.messagetime,
m.status
FROM messages m
INNER JOIN
(
SELECT uid id FROM friends WHERE status = 1 AND fid = 1
UNION ALL
SELECT fid FROM friends WHERE status = 1 AND uid = 1
) friends ON m.fid = friends.id OR m.uid = friends.id
INNER JOIN users senders ON m.uid = senders.id
INNER JOIN users recievers ON m.fid = recievers.id
WHERE m.uid = 1
OR m.fid = 1
ORDER BY m.messagetime ASC OR DESC
例如,这将为您提供:
| FROM | TO | ID | BODY | MESSAGETIME | STATUS |
--------------------------------------------------
| Me | B | 1 | hiiii | 2012-12-01 | 1 |
| c | Me | 7 | sadfds | 2012-12-01 | 1 |
| Me | B | 8 | ddd | 2012-12-10 | 1 |
这个查询是如何工作的?
查询:
SELECT uid id FROM friends WHERE status = 1 AND fid = myuserid
UNION ALL
SELECT fid FROM friends WHERE status = 1 AND uid = myuserid
会给你你朋友的名单,你的朋友是:
- 用户向您发送了友谊请求并接受了,或者
- 用户向他发送友谊请求,他接受了。
这就是为什么我在您的用户 ID 中使用 a 的原因UNION ALL
,fid =
并且我还假设这status = 1
意味着友谊请求被接受。
这些是你的朋友。然后,要获取您已向其发送消息或从其接收消息的朋友列表,我们必须将此结果集与messages
表连接起来。但是要获取发送给您的消息或您发送的消息,我们必须选择加入条件m.fid = friends.id OR m.uid = friends.id
。而已。