【问题标题】:Show all rows with 0 if no records found on second table如果在第二个表上没有找到记录,则显示所有行为 0
【发布时间】:2023-03-15 06:11:01
【问题描述】:

我需要查看表 A 中的所有记录,如果在表 B 上没有找到匹配的记录,则显示 0,对应的值为 A。

SELECT r.date
     , l.total_user
  FROM daterange r
  LEFT 
  JOIN logs l
    ON r.date = l.created_date
 WHERE r.date BETWEEN '2020-09-14' AND '2020-11-14' AND   l.view_id =(SELECT view_id from logs where user_id = 63)

在上面的查询中,日志表中不存在一些记录,但我也需要 0 和日期。

请知道如何解决这个问题

我需要日期范围表中从“2020-09-14”到“2020-11-14”的所有日期

【问题讨论】:

    标签: mysql sql left-join sql-null


    【解决方案1】:

    大概,你想要coalesce()

    select d.date, coalesce(l.total_user, 0) as total_user
    from daterange d 
    left join logs l on d.date = l.created_date
    where d.date between '2020-09-14' and '2020-11-14'
    

    logs 表中的给定date 没有匹配项时,这会为total_user 返回0 而不是null。当然,这假定列 total_user 是数字数据类型开始的。

    请注意,表别名使查询更易于编写和阅读。

    【讨论】:

    • 这缺少 '2020-09-14' 并且如果我使用另一种条件,例如 select d.date, coalesce(l.total_user, 0) as total_user from daterange d left join logs l on d .date = l.created_date 其中 d.date 介于 '2020-09-14' 和 '2020-11-14' AND l.view_id =(SELECT view_id from logs where user_id = 63)。它给出的记录很少
    【解决方案2】:

    你可以使用 IFNULL() 函数。

    SELECT r.date
         , IFNULL(l.total_user, 0)
      FROM daterange r
      LEFT 
      JOIN logs l
        ON r.date = l.created_date
     WHERE r.date BETWEEN '2020-09-14' AND '2020-11-14' AND   l.view_id =(SELECT 
     view_id from logs where user_id = 63)
    

    【讨论】:

    • 这缺少 '2020-09-14' 并且如果我使用另一种条件,例如 select d.date, coalesce(l.total_user, 0) as total_user from daterange d left join logs l on d .date = l.created_date 其中 d.date 在 '2020-09-14' 和 '2020-11-14' 之间并且 l.view_id =(SELECT view_id from logs where user_id = 63)。它给出的记录很少——
    • 这个查询工作正常,但没有给我所有的结果。这只是现在给我匹配的记录
    • 您可以编辑问题以使其更具描述性吗?您可以添加预期和实际结果。
    猜你喜欢
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2021-10-06
    相关资源
    最近更新 更多