0

我有三个表,需要获取用户 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 也是收件人的消息,并且只收到 Peter 不包括在内的消息。

4

2 回答 2

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
于 2012-05-30T12:52:38.077 回答
0
SELECT m.* FROM Messages m
JOIN messageRecipients r ON
r.idMessage = m.idMessage
    AND r.idUserRecipient <> 2
WHERE m.idUserSender <> 2

您当然可以参数化此查询以排除任何idUser

于 2012-05-30T12:51:48.887 回答