【问题标题】:SQL- show null, 0 and not present valueSQL- 显示空值、0 和非当前值
【发布时间】:2020-11-03 10:50:15
【问题描述】:

我需要帮助。

我有sql代码:

SELECT app_users.name,COUNT(owner)
FROM app_users
INNER JOIN app_tickets
ON app_tickets.owner = app_users.id
where app_tickets.status IN (0,1,2,4,5)
GROUP BY app_users.name

此代码显示如下值:

Adam Smith 12
Brad Smith 23
Nancy Smith 3

但我需要像这样展示价值

Adam Smith 12
Ann Smith 0
Brad Smith 23
Nancy Smith 3
Peter Smith 0

我尝试使用 IFNULL() 和 COALESCE() 但没有帮助

【问题讨论】:

    标签: mysql sql count subquery left-join


    【解决方案1】:

    那是left join:

    select u.name, count(t.owner) cnt
    from app_users u
    left join app_tickets t
        on  t.owner = u.id
        and t.status in (0, 1, 2, 4, 5)
    group by u.name, u.id
    

    您也可以使用相关子查询:

    select u.name,
        (select count(*) from app_tickets t where t.owner = u.id and t.status in (0,1,2,4,5)) cnt
    from app_users u
    

    此查询将利用app_tickets(owner, status) 上的索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 2021-09-28
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 2012-12-06
      相关资源
      最近更新 更多