如果表1中的联接字段不为空,我想联接数据库中的三个表。如果为空,我只想要表1的结果。
Table1
----------------------
id | name | table2_id|
----------------------
1 John 1
2 Frank 1
3 Mary 2
4 Susan null
Table2
----------------------
id | City | table3_id|
----------------------
1 Berlin 2
2 Paris 3
3 Rome 1
3 Oslo 1
Table3
-------------------------------
id | title | description |
-------------------------------
1 Great place Some tekst
2 Fun town Some other text
3 Don't go More text
我正在使用此查询:
SELECT a.name, b.city, c.title, c.description
FROM table1 AS a
LEFT JOIN table2 AS b ON b.id = a.table2_id
LEFT JOIN table3 AS c ON c.id = b.table3_id
WHERE a.id = 1
只要table1具有table2_id,此方法就可以正常工作。如果是John,它将返回
John, Berlin, Great Place, Some text
但是在Susan的情况下,table2_id为null,因此它返回空结果。但我想因此得到“苏珊”。