mysql - SQL-显示 null、0 和非当前值

标签 mysql sql count subquery left-join

我需要帮助。

我有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/

相关文章:

php - MySQL Process List - 提高性能 - 锁定问题

SQL 计数不存在的项目

php - 我想显示各个俱乐部的所有球员,但在 laravel 的表格中遇到一些问题

mysql - 将大量扩展插入转换为 mysql 的简单插入

mysql - 在 perl/tk 上使用线程来避免窗口卡住/不响应

javascript - Replace() 标签在 JavaScript 中不起作用

sql - PostgreSQL:如何阅读并行解释分析(行与单线程不匹配)

mysql - 值为 0 时不打印结果

python - 在 Pandas 上以不同方式计算整数和字符串

mysql用单​​个查询连接案例计数