我有三个表,需要获取用户PETER不是发件人且不是收件人的邮件。
表'消息'
idMessage | bodyText | idUserSender
---------------------------------------------
1 | This is message 1 | 2
2 | This is message 2 | 1
3 | This is message 3 | 1
表'用户'
idUser | name
-------------------
1 | John
2 | Peter
3 | Marco
表'messageRecipients'
idMessage | idUserRecipient
----------------------------
1 | 1
1 | 3
2 | 1
2 | 3
3 | 2
3 | 3
所以结果集应该是:
idMessage | bodyText | idUserSender
---------------------------------------------
2 | This is message 2 | 1
我尝试过:
SELECT * FROM messages AS M
LEFT JOIN
(
SELECT * FROM users WHERE idUser <> 2
) AS allUsersWithoutPeter ON M.idUserSender = allUsersWithoutPeter.idUser
GROUP BY M.idMessage
并且得到了彼得不是发件人的消息,但是不知道如何除了Peter也是收件人的消息之外,并且只获得不包括Peter的消息。
答案 0 :(得分:0)
SELECT m.* FROM Messages m
JOIN messageRecipients r ON
r.idMessage = m.idMessage
AND r.idUserRecipient <> 2
WHERE m.idUserSender <> 2
您当然可以参数化此查询以排除任何idUser
答案 1 :(得分:0)
select
m.*
from
messages m
join
users u on u.idUser != m.idUserSender and u.name='Peter'
join
messageRecipients mr on mr.idMessage = m.idMessage and mr.idUserRecipient != u.idUser