我设法使用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`
第一个查询(如果$ user_id = 2)返回以下结果:
第二个查询(如果$ user_id = 2)什么也不返回
我怎么知道2也向4和5发送消息?
答案 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