连接为A并根据其FK选择A或B.

时间:2013-10-16 11:22:26

标签: sql sqlite

我有三张桌子:

IDcontacts | FirstName | LastName
----------------------------------
1          | Walt      | Ne


IDcompany | CompanyName
------------------------
1         | Universe


IDowner  | IDcontacts | IDcompany
---------------------------------
1        | 1          | NULL
2        | NULL       | 1
3        | NULL       | NULL


我需要一个查询,它会给我以下输出:

IDoutput | Name
--------------------
1        | Walt Ne
2        | Universe
3        | NULL

1 个答案:

答案 0 :(得分:1)

要进行连接并获得一半结果,即使其他记录不存在,也请使用外连接。

要选择列表的第一个非NULL值,请使用COALESCE:

SELECT IDowner as IDoutput,
       COALESCE(FirstName || ' '  || LastName, CompanyName) AS Name
FROM Owner
LEFT JOIN Contacts ON Owner.IDcontacts = Contacts.IDcontacts
LEFT JOIN Company  ON Owner.IDcompany  = Company .IDcompany