SQL查询返回列为空(如果找不到)

时间:2019-03-08 09:19:22

标签: sql postgresql

此查询将在找到该组织的摄像机后返回所有组织,否则将不返回一行。

SELECT org.id as organization_id, 
 cam.id as device_id,
 org.slug as organization_slug 
 FROM accounts_organization org 
 INNER JOIN devices_camera cam on org.id=cam.owner_id 
 WHERE org.slug IN ('org1','org2') and cam.unique_identifier = '123'

如何更改此设置,以便它将返回所有查询的组织,但是如果没有此类相关的摄像机,则该列字段将为空,但仍将显示该行?

1 个答案:

答案 0 :(得分:2)

inner join更改为左联接,并将cam.unique_identifier = '123'更改为on子句

  SELECT org.id as organization_id, 
 cam.id as device_id,
 org.slug as organization_slug 
 FROM accounts_organization org 
 left JOIN devices_camera cam on org.id=cam.owner_id and  cam.unique_identifier = '123'
 WHERE org.slug IN ('org1','org2') 
相关问题