我有數據庫的模式是這樣的:獲得通過收件人的螺紋消息
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
所面臨的挑戰是這樣的,我想有約翰,特洛伊和馬特因爲只有收件人的郵件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)作爲結果。
我做錯了什麼?有人能啓發我嗎?
非常感謝你, 約翰
我也試過這個,但它也給出'2'的結果。不是我想要的。 – jobun 2012-04-17 06:42:26
您是否可以更新問題並提供您期望的輸出? – Arion 2012-04-17 06:45:35
我已經更新了我期望的問題和輸出。感謝您的回覆。 – jobun 2012-04-17 06:59:53