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

挑战在于,我想获得一个只有 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)。

我做错什么了?有人可以启发我吗?

非常感谢,约翰

4

3 回答 3

1

我不确定你想要什么。但是一列不能是三件事。你可以只使用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'
于 2012-04-17T06:38:16.970 回答
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')
于 2012-04-17T06:40:27.817 回答
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')
于 2012-04-17T07:14:47.140 回答