【问题标题】:Can't get records to show with date filter, when there is no related records当没有相关记录时,无法使用日期过滤器显示记录
【发布时间】:2021-06-13 04:31:15
【问题描述】:

不知道具体如何进行这项工作。我有多个相关表。用户、客户、任务和时间记录。我试图为用户完成的是,显示他们拥有的所有客户,并总结当月在该客户上花费的所有时间。

即使当月没有时间记录,它也应该显示给客户端。

当我逐步构建查询时...它一直有效,直到我添加了日期大于的位置。所以这行得通(无论是否有时间记录,它都会显示所有客户,但无论日期如何,它都会汇总小时数。

SELECT Clients.company_name, 
       Clients.logo, 
       Clients.id, 
       SUM(Timerecords.manual_input_hours) as hours_spent_on_client
FROM Clients
INNER JOIN
Mapping_User_To_Clients
ON Clients.id = Mapping_User_To_Clients.client_id
    LEFT OUTER JOIN
    Timerecords
    ON Clients.id = Timerecords.client_id
WHERE Mapping_User_To_Clients.user_id = 5
GROUP BY Clients.company_name, 
         Clients.logo, 
         Clients.id;

当我添加的日期大于当月的第一天时,它只返回具有完成小时数的时间记录的客户端。还没有时间记录的客户消失了。我对如何进行这项工作感到困惑(我硬编码了 user_id(5) 和 date(2021-06-01) 以测试查询,这些将是变量)。

SELECT Clients.company_name, 
       Clients.logo, 
       Clients.id, 
       SUM(Timerecords.manual_input_hours) as hours_spent_on_client
FROM Clients
INNER JOIN
Mapping_User_To_Clients
ON Clients.id = Mapping_User_To_Clients.client_id
    LEFT OUTER JOIN
    Timerecords
    ON Clients.id = Timerecords.client_id
WHERE Mapping_User_To_Clients.user_id = 5 and Timerecords.time_start >= '2021-06-01'
GROUP BY Clients.company_name, 
         Clients.logo, 
         Clients.id;


【问题讨论】:

  • and Timerecords.time_start >= '2021-06-01' 放在LEFT JOIN 的ON 子句中。

标签: sql postgresql


【解决方案1】:

首先,我强烈建议使用表别名,以便查询更易于编写和阅读。

其次,需要将最后一张表的过滤条件移到ON子句中。否则LEFT JOIN 会变成INNER JOIN(即NULL 值被过滤掉):

SELECT cl.company_name, cl.logo, cl.id, 
       SUM(tr.manual_input_hours) as hours_spent_on_client
FROM Clients cl JOIN
     Mapping_User_To_Clients utc
     ON cl.id = utc.client_id LEFT JOIN
     Timerecords tr
     ON cl.id = tr.client_id AND
        tr.time_start >= '2021-06-01'
WHERE utc.user_id = 5 
GROUP BY cl.company_name, cl.logo, cl.id;

【讨论】:

  • 谢谢 Gordon,我也非常喜欢关于使用表别名的提示。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多