获取收件人的线程消息

时间:2012-04-17 06:34:35

标签: mysql sql foreign-keys primary-key

我有这样的数据库模式:

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)。

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

非常感谢,     约翰

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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')

答案 2 :(得分: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')