【问题标题】:Multiple joins on the same table, Results Not Returned if Join Field is NULL同一表上的多个连接,如果连接字段为 NULL,则不返回结果
【发布时间】:2020-07-25 09:44:32
【问题描述】:
SELECT organizations_organization.code as organization,
core_user.email as Created_By,
assinees.email as Assigned_To,
from tickets_ticket 
JOIN organizations_organization on tickets_ticket.organization_id = organizations_organization.id
JOIN core_user on tickets_ticket.created_by_id  = core_user.id 
Left JOIN core_user as assinees on assinees.id = tickets_ticket.currently_assigned_to_id 

在上述查询中,如果tickets_ticket.currently_assigned_to_id 为空,则不返回tickets_ticket 中的那一行

> Records In tickets_ticket = 109
> Returned Records = 4 (out of 109 4 row has value for currently_assigned_to_id  rest 105 are null )
> Expected Records = 109 (with nulll set for  Assigned_To)

注意我正在尝试在同一个表上实现多个连接

【问题讨论】:

  • 只是为了让事情更清楚,INNER 关键字是可选的。 IE。 INNER JOINJOIN 相同。

标签: sql postgresql join


【解决方案1】:

LEFT JOIN 不能杀死输出记录, 你的问题在这里:

JOIN core_user on tickets_ticket.created_by_id = core_user.id 

这个连接会杀死不匹配的记录 试试

LEFT JOIN core_user on tickets_ticket.created_by_id = core_user.id  

【讨论】:

    【解决方案2】:

    首先,这不是您正在运行的实际代码。 from 子句之前有一个逗号,会导致语法错误。如果您遗漏了 where 子句,那么这可以解释为什么您看不到任何行。

    当使用left joins 时,first 表上的条件进入where 子句。后续表的条件放在on 子句中。

    也就是说,where 子句可能不是问题所在。我建议从第一个表开始使用left joins 以及表别名:

    select oo.code as organization, cu.email as Created_By, a.email as Assigned_To,
    from tickets_ticket tt left join
         organizations_organization oo
         on tt.organization_id = oo.id left join
         core_user cu
         on tt.created_by_id = cu.id left join
         core_user a
         on a.id = tt.currently_assigned_to_id ;
    

    我怀疑您的数据模型中有意外的数据——也许是糟糕的组织,也许是糟糕的created_by_id。保留所有的票,看看缺少什么。

    也就是说,您可能应该在结果集中包含 tt.id 之类的内容来识别特定的票证。

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多