我需要帮助。
我有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
但我需要像这样展示值(value)
Adam Smith 12
Ann Smith 0
Brad Smith 23
Nancy Smith 3
Peter Smith 0
我尝试使用 IFNULL() 和 COALESCE() 但没有帮助
最佳答案
这是一个左连接
:
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)
上的索引。
关于mysql - SQL-显示 null、0 和非当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64661367/