在标准不匹配的情况下返回空

时间:2017-03-06 14:12:58

标签: postgresql

我有以下PGSQL声明,意味着从多个清单返回所有项目

SELECT 
    cl.id as checklist_id,
    ci.id checklist_item_id,
    ci.name,
    ci.details,
    cil.id as logid,
    cil.date_added,
    cs.id as schedule_id,
    a.id as account_id, a.first_name || ' ' || a.last_name as full_name
FROM checklist_item ci
    LEFT JOIN checklist cl ON cl.id = ci.checklist_id
    LEFT JOIN checklist_item_log cil ON cil.checklist_item_id = ci.id
    LEFT JOIN checklist_schedule cs ON cs.id = cil.checklist_schedule_id
    LEFT JOIN account a ON a.id = cil.account_id
--WHERE cil.date_added >= now()::date + interval '1h' OR cil.date_added is null
GROUP BY cl.id, ci.id, cil.id, cs.id, a.id

注释掉的WHERE子句应该只选择日期为今天的项目或者为空。 enter image description here

虽然这个功能很好,但是我还需要它包含以前日期的项目,但是作为一个空的结果。

enter image description here

对于上面的结果,[3] chairs应该在checklist_item_log表中返回null结果。这可能吗?

如果您需要更多说明,请告诉我

2 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,你的解决方案是:

SELECT 
    cl.id as checklist_id,
    ci.id checklist_item_id,
    ci.name,
    ci.details,
    cil.id as logid,
    cil.date_added,
    cs.id as schedule_id,
    a.id as account_id, a.first_name || ' ' || a.last_name as full_name
FROM checklist_item ci
    LEFT JOIN checklist cl ON cl.id = ci.checklist_id
    LEFT JOIN checklist_item_log cil ON cil.checklist_item_id = ci.id
    LEFT JOIN checklist_schedule cs ON cs.id = cil.checklist_schedule_id
    LEFT JOIN account a ON a.id = cil.account_id
                           AND (cil.date_added >= now()::date + interval '1h' 
                                OR cil.date_added is null)
GROUP BY cl.id, ci.id, cil.id, cs.id, a.id

答案 1 :(得分:0)

使用两个查询,一个如上所述,另一个只选择上面描述的旧查询。

然后在查询之间编写UNION ALL以将它们组合到单个查询中。

相关问题