按字段计算mysql组的计数记录

时间:2017-03-01 12:59:55

标签: mysql sql select

MySQL中的表格 http://joxi.ru/5mdWRV8tyQzyr1

我的程序传递数组用户

$ids = [1, 3, 7];

我对表格的查询:

SELECT responsible_id, count(id) as count
from test
WHERE active = 1
  AND status = 3
  AND responsible_id in (1, 3, 7)
GROUP BY responsible_id
ORDER BY count(id)

我得到结果http://joxi.ru/vAWYGq0IMxdjmW

但是,如果桌面上不存在,我还需要第一行使用responsible_id = 7和count = 0。

1 个答案:

答案 0 :(得分:1)

要做你想做的事,请使用left join

SELECT v.responsible_id, count(t.id) as count
FROM (SELECT 1 as responsible_id UNION ALL
      SELECT 3 as responsible_id UNION ALL
      SELECT 7 as responsible_id
     ) v LEFT JOIN
     test t
     ON t.responsible_id = v.responsible_id AND
        t.active = 1 AND
        t.status = 3
GROUP BY v.responsible_id
ORDER BY count(id);

请注意WHERE中的条件已移至ON子句。