繁体   English   中英

加入两个以上的表

[英]Join more than two tables

我正在尝试加入 2 个表,在 1 个表中可能有也可能没有相应的值。但我需要加入表并将字段列为空。

我尝试将表作为左连接加入。但是如果第二个表中有两个条目对应于第一个表的值,则第一个表数据将显示两次。

如果另一个表中有两个数据或另一个表中没有数据,我只需要显示一次,但它应该显示为空。

这是我的 sql 查询。

        SELECT *,incident.incident_id as incidentid
        FROM register_incident AS incident
        LEFT JOIN incident_images AS im ON im.incident_id= 
        incident.incident_id
        WHERE incident.state='Active'

如果另一个表中没有相应的行,我只需要显示一次每个数据,但第二个表中的字段列表为空。

如果另一个表中有多于一行,则也将第一个表中的每一行显示一次,第二个表中的一个条目。

您可以使用 select distinct 只获取一行,例如(将 select 限制为 indicent_id ,但您可以添加您需要的 distinctcolumn ):

 SELECT *,incident.incident_id as incidentid
    FROM register_incident AS incident
    LEFT JOIN (
      select distinct incident_id from 
      incident_images
      WHERE incident.state='Active' ) t   ON t.incident_id= incident.incident_id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM