2012-04-17 54 views
1

我有數據庫的模式是這樣的:獲得通過收件人的螺紋消息

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)作爲結果。

我做錯了什麼?有人能啓發我嗎?

非常感謝你, 約翰

回答

1

我真的不知道你想要什麼。但是一列不能是3件事。您可以只使用IN語法。就像這樣:

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 IN('John','Troy','Matt') 

還是OR語法如下:

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' 
     OR mr2.RECIPIENT = 'Troy' 
     OR mr2.RECIPIENT = 'Matt' 
    ) 

編輯

我仍然不知道你想要什麼。但它聽起來有點像你想是這樣的:

SELECT 
    m.ID AS MESSAGE_ID, 
    m.CREATOR, 
    mr.RECIPIENT, 
    mr2.RECIPIENT 
FROM 
    messages AS m 
    LEFT JOIN message_recipients AS mr 
     ON m.ID=mr.MESSAGE_ID 
     AND mr.RECIPIENT='Troy' 
    LEFT JOIN message_recipients AS mr2 
     ON m.ID=mr2.MESSAGE_ID 
     AND mr2.RECIPIENT='Matt' 
WHERE 
    m.CREATOR='John' 
+0

我也試過這個,但它也給出'2'的結果。不是我想要的。 – jobun 2012-04-17 06:42:26

+0

您是否可以更新問題並提供您期望的輸出? – Arion 2012-04-17 06:45:35

+0

我已經更新了我期望的問題和輸出。感謝您的回覆。 – jobun 2012-04-17 06:59:53

0

我認爲你應該使用OR代替AND

嘗試以下:

SELECT mr1.MESSAGE_ID 
FROM message_recipients mr1 LEFT JOIN message_recipients mr2 
ON mr1.MESSAGE_ID = mr2.MESSAGE_ID 
WHERE mr1.RECIPIENT = mr2.RECIPIENT 
    AND (mr2.RECIPIENT = 'John' 
    OR mr2.RECIPIENT = 'Troy' 
    OR mr2.RECIPIENT = 'Matt') 
+0

嘗試使用左連接而不是簡單連接。嘗試查詢張貼在這裏 – 2012-04-17 06:49:45

0

給它一個試戴

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 in ('Troy','Matt')