sql:使用相同的键左连接multitables

时间:2014-08-24 21:53:50

标签: mysql sql left-join

鉴于以下三个表:

表1

id   name      observation
--------------------------
1    mario     serial
2    samantha  drogue dealer
3    jennifer  prostitute
4    megan     nun

表2

id   person_id  contact
-------------------------
1    2          jefferson

表3

id   person_id salary
---------------------
1     2        180 000
2     4        0

我希望输出为

id   name      observation    contact     salary
-------------------------------------------------
1    mario     serial          NULL       NULL
2    samantha  drogue dealer   jefferson  180 000
3    jennifer  prostitute      NULL       NULL
4    megan     nun             NULL       0

我应该在这里多次使用左连接吗? 怎么做?

1 个答案:

答案 0 :(得分:1)

您的主表是您的Table1。次要的是接触和工资。通过从主要到次要方式进行LEFT-JOIN,无论右侧是否匹配,都会在左侧给出记录。连接基于辅助表的“person_id”

select
      t1.id,
      t1.name,
      t1.observation,
      t2.contact,
      t3.salary
   from
      table1 t1
         LEFT JOIN table2 t2
            on t1.id = t2.person_id
         LEFT JOIN table3 t3
            on t1.id = t3.person_id