MySQL查询列出我已发送消息或收到消息的朋友

时间:2012-12-09 12:18:32

标签: mysql sql

以下是我的两张表:

TABLE: friends

'id' // primary id, auto increment
'uid' // user id who sent friend request
'fid' // friend id who received friend request
'status' //status of friendship, 1=active

TABLE: messages

'id' // message id (primary id), auto increment
'uid' // user who sent the message
'fid' // friend who received the message
'time' // time when the message was sent
'status' // status of message, read or unread.

我想只显示我发送消息的朋友列表,或者在发送最后一条消息时(由朋友或我发送)收到的消息。一个朋友应该只列一次。我该怎么做?

1 个答案:

答案 0 :(得分:4)

  

我想只显示我向其发送消息的朋友列表   收到的消息来自最后一条消息的发送时间(由   朋友或我。)

试试这个:

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

SQL Fiddle Demo

例如,这会给你:

| 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

会给你你的朋友名单,你的朋友是:

  • 用户向您发送了友情请求并已接受,或
  • 向您发送友情请求的用户,他接受了。

这就是我使用UNION ALL fid =您的用户ID的原因,我还假设status = 1表示接受了友情请求。

这些是你的朋友。然后,要获取已向其发送消息或从中接收消息的朋友列表,我们必须将此结果集与messages表一起加入。但是要获取发送给您的消息或您发送的消息,我们必须选择连接条件m.fid = friends.id OR m.uid = friends.id。多数民众赞成。