我有这样的数据库模式:
users
USERNAME (PK), SEX
Alex, F
John, M
Troy, M
Matt, M
messages
ID (PK), CREATOR (FK users), DATE_CREATED
1, John, 2012-04-15
2, Troy, 2012-04-16
message_recipients
ID, MESSAGE_ID (FK messages), RECIPIENT (FK users), DATE
1, 1, John, 2012-04-15
2, 1, Troy, 2012-04-15
3, 1, Matt, 2012-04-15
4, 2, Alex, 2012-04-16
4, 2, John, 2012-04-16
挑战在于,我想获得一个只有 John、Troy 和 Matt 作为收件人的消息 ID。
这是我的查询:
SELECT mr1.MESSAGE_ID
FROM message_recipients mr1, message_recipients mr2
WHERE mr1.MESSAGE_ID = mr2.MESSAGE_ID
AND mr1.RECIPIENT = mr2.RECIPIENT
AND mr2.RECIPIENT = 'John'
AND mr2.RECIPIENT = 'Troy'
AND mr2.RECIPIENT = 'Matt'
上面的 SQL 显示没有结果。
如果我执行此查询:
SELECT mr1.MESSAGE_ID
FROM message_recipients mr1, message_recipients mr2
WHERE mr1.MESSAGE_ID = mr2.MESSAGE_ID
AND mr1.RECIPIENT_ID = mr2.RECIPIENT_ID
AND (mr2.RECIPIENT_ID = 'John'
OR mr2.RECIPIENT_ID = 'Troy'
OR mr2.RECIPIENT_ID = 'Matt')
GROUP BY mr1.MESSAGE_ID
结果:
MESSAGE_ID
1
2
上面的结果是不正确的,因为我想看到的结果只有 1 (MESSAGE_ID)。
我做错什么了?有人可以启发我吗?
非常感谢,约翰