mysql得到的用户没有任何消息给某个用户?

时间:2018-06-29 13:18:50

标签: php mysql

我有以下messagesenter image description here

我设法使用php中的此查询来获取与某个用户有消息的用户

SELECT ReceiverUserId,SenderUserId,Name,Email,
    Count(CASE WHEN IsReaded = 0 THEN 1 END) AS messagesNum,
    Message,MessageDateTime 
FROM (SELECT * 
      FROM messages 
      ORDER BY MessageDateTime DESC) AS footbl
JOIN users ON users.id =footbl.SenderUserId
WHERE ReceiverUserId=".$user_id." 
GROUP BY SenderUserId

它返回了与特定用户($ user_id)有消息的用户 但是它并没有向用户返回该特定用户向他们发送的邮件没有任何回复,为此我尝试了另一个查询

SELECT * FROM `messages` as m
    join `users` on m.`ReceiverUserId`=`users`.Id
    WHERE (select count(*) from `messages` as s
    WHERE m.`SenderUserId`=s.`ReceiverUserId` ) = 0
    AND `SenderUserId`=".$user_id.
    " group by `SenderUserId`

例如,如果我有以下数据  enter image description here

第一个查询(如果$ user_id = 2)返回以下结果:

enter image description here

第二个查询(如果$ user_id = 2)什么也不返回

我怎么知道2也向4和5发送消息?

3 个答案:

答案 0 :(得分:1)

我理解您的问题,以便您希望获得与某个用户$user_id联系的用户的所有用户ID,即向他/她写消息或从他/她接收消息。

首先,让我们获取从$user_id接收消息的用户的所有ID。

SELECT ReceiverUserId AS ContactId FROM messages WHERE SenderUserId = $user_id

然后,我们希望向$user_id发送消息的所有用户ID。

SELECT SenderUserId AS ContactId FROM messages WHERE ReceiverUserId = $user_id

现在我们要合并两个结果。

SELECT ReceiverUserId AS ContactId FROM messages WHERE SenderUserId = $user_id
UNION
SELECT SenderUserId AS ContactId FROM messages WHERE ReceiverUserId = $user_id

默认情况下,UNION会删除重复的行。

上面的查询应返回$user_id = 2的以下结果:

| ContactId |
+-----------+
|         1 |
|         3 |
|         4 |
|         5 |
+-----------+ 

如果您希望没有 的用户的ID与特定用户联系,则可以在另一个查询中使用上述查询的结果:

SELECT Id
FROM users
WHERE Id NOT IN(
    SELECT ReceiverUserId AS ContactId FROM messages WHERE SenderUserId = $user_id
    UNION
    SELECT SenderUserId AS ContactId FROM messages WHERE ReceiverUserId = $user_id
)

答案 1 :(得分:0)

SELECT id
    FROM Users u
    WHERE NOT EXISTS ( SELECT 1 FROM Messages
                          WHERE ReceiverUserId = u.id
                            AND SenderUserId = 1234 )

有益:

Messages:  INDEX(SenderUserId, ReceiverUserId)  -- in either order

(不知道Is...的语义,我没有把它们扔进去。)

答案 2 :(得分:0)

您可以尝试编写NOT EXISTS子查询以达到期望。

SELECT * 
FROM messages m INNER JOIN users u 
ON m.ReceiverUserId = u.id
WHERE NOT EXISTS(
   SELECT 1 
   FROM messages t1
   WHERE  
      m.SenderUserID = t1.ReceiverUserId 
   AND
      m.ReceiverUserId = t1.SenderUserID
) AND 
m.SenderUserID = $user_id  

sqlfiddle:http://sqlfiddle.com/#!9/104dae/24