MySQL棘手的三重连接

时间:2014-05-08 04:47:48

标签: mysql

这是我拥有的三张桌子:
电子邮件

    +----------+--------------+------+-----+---------+----------------+
    | Field    | Type         | Null | Key | Default | Extra          |
    +----------+--------------+------+-----+---------+----------------+
    | emailID  | int(11)      | NO   | PRI | NULL    | auto_increment |
    | subject  | varchar(100) | YES  |     | NULL    |                |
    | body     | text         | YES  |     | NULL    |                |
    | userID   | int(11)      | NO   |     | NULL    |                |
    | date     | timestamp    | YES  |     | NULL    |                |
    +----------+--------------+------+-----+---------+----------------+

    +----------+-------------+------+-----+---------+----------------+
    | Field    | Type        | Null | Key | Default | Extra          |
    +----------+-------------+------+-----+---------+----------------+
    | userID   | int(11)     | NO   | PRI | NULL    | auto_increment |
    | name     | varchar(50) | YES  |     | NULL    |                |
    | email    | varchar(50) | NO   |     | NULL    |                |
    | relation | varchar(50) | YES  |     | NULL    |                |
    +----------+-------------+------+-----+---------+----------------+

toLine

    +---------+---------+------+-----+---------+-------+
    | Field   | Type    | Null | Key | Default | Extra |
    +---------+---------+------+-----+---------+-------+
    | emailID | int(11) | NO   | PRI | NULL    |       |
    | userID  | int(11) | NO   | PRI | NULL    |       |
    +---------+---------+------+-----+---------+-------+

字段emails.userID是发件人的ID,因此电子邮件来自谁。

我需要的是一个查询,它会将我发送的电子邮件(relation ='研究员')发送给我的课程主管(关系='课程主管')。我不知道如何进行连接,所以我可以用两种不同的方式使用关系字段。

我已经尝试了查询:

SELECT count(emails.emailID)
FROM emails
LEFT JOIN people ON emails.userID = people.userID
WHERE people.relation='researcher';

这让我收到了我发送的所有电子邮件,但是我无法根据发送电子邮件的人来确定如何进一步过滤这些电子邮件。

2 个答案:

答案 0 :(得分:1)

请尝试此查询:

select distict e.* from emails e
join `toLine` t on t.`emailID` = e.`emailID`
join people pto on pto.`userID` = t.`userID`
join people pfrom on e.`userID` = pfrom.`userID`
where pfrom.relation = 'researcher' and pto.relation = 'course director'

答案 1 :(得分:0)

如果您希望研究员发送的所有电子邮件到课程总监,请尝试此操作...

SELECT e.* FROM emails e
INNER JOIN people senders
    ON e.userID = senders.userID
WHERE senders.relation = 'researcher'
AND EXISTS (
    SELECT 1 FROM toLine t
    INNER JOIN people recipients 
        ON t.userID = recipients.userID
    WHERE e.emailID = t.emailID
    AND recipients.relation = 'course director'
)

我已使用EXISTS条款,因此您最终不会有重复的emails条记录。