Reputation: 157
I have database schemas like this:
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
The challenge is this, I want to get a message ID that has John, Troy and Matt as the recipients only.
This is my query:
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'
The SQL above shows No Results.
If I do this query:
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
The results:
MESSAGE_ID
1
2
The above results are incorrect because what I want to see is only 1 (MESSAGE_ID) as the result.
What did I do wrong? Could someone enlighten me?
Thank you very much, John
Upvotes: 1
Views: 75
Reputation: 4069
Give it a try-
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')
Upvotes: 0
Reputation: 31249
I am not really sure what you want. But a column can't be 3 things. You can just the IN
syntax . Like this:
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 the OR
syntax like this:
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'
)
EDIT
I am still not sure what you want. But it kinda sound like you want something like this:
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'
Upvotes: 1
Reputation:
I think you should Use OR
instead of AND
Try below :
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')
Upvotes: 0