如何从联结表多次引用单个表

时间:2019-07-16 02:02:03

标签: mysql sql

我有两个表:

contacts table:
----------------------------------------------
| contactId | firstName | lastName | birthday |
----------------------------------------------

birthdayEvents table:
---------------------------------------------
| birthdayEvtId | birthdayPerson | contactee |
---------------------------------------------

在birthdayEvents表中,birthdayPerson和contactee都是引用contacts.contactId值的外键。

我的BirthdayEvents表的结构使得一个BirthdayPerson可以有多个联系人(例如,这些人是被邀请参加聚会的人)

birthdayEvents:
---------------------------------------------
| 1 | 1 | 2 |
---------------------------------------------
| 2 | 1 | 3 |
---------------------------------------------
| 3 | 1 | 4 |
---------------------------------------------
| 4 | 2 | 1 |
---------------------------------------------
| 5 | 2 | 4 |
---------------------------------------------
| 6 | 2 | 5 |
etc...

我想要一个查询,其中列出了生日人员的姓名和每个联系人的姓名。我已经尝试过了

SELECT bp.firstName, bp.lastName, c.firstName, c.lastName
FROM contacts AS bp
INNER JOIN birthdayEvents AS be
INNER JOIN contacts AS c
WHERE (bp.contactId = be.birthdayPerson) AND 
(c.contactId = be.contactee)

但是它不起作用,出现语法错误。我不知道如何编写此查询。

1 个答案:

答案 0 :(得分:1)

您可以尝试将两次加入到contacts表中:

SELECT
    b.birthdayEvtId,
    CONCAT(c1.lastName, ', ', c1.firstName) AS birthday_person,
    CONCAT(c2.lastName, ', ', c2.firstName) AS contactee
FROM birthdayEvents b
LEFT JOIN contacts c1
    ON b.birthdayPerson = c1.contactId
LEFT JOIN contacts c2
    ON b.contactee = c2.contactId;