MySQL在同一个表中计数,包括零计数值

时间:2013-04-02 07:10:35

标签: mysql count

我有这个包含数据的表结构:

INSERT INTO `test` (`id`, `email`, `id_user_ref`, `name`) VALUES
(1, 'email@gmail.com', NULL, 'Mike'),
(2, 'email2@gmail.com', '1', 'Jhonny'),
(3, 'email3@gmail.com', '1', 'Michael'),
(4, 'email4@gmail.com', '2', 'Jorhe'),
(5, 'email5@gmail.com', '3', 'Mia');

我需要使用此查询计算所有用户的id_user_ref:

SELECT id, COUNT(name) AS refNr FROM test GROUP BY id_user_ref
HAVING id_user_ref IS NOT NULL;

这样可行,但问题是即使计数结果为0,我也需要显示所有结果。

我在同一张桌子上尝试了几个左连接但没有任何成功。

输出应为:

id  refNr
1    2
2    1
3    1
4    0
5    0

2 个答案:

答案 0 :(得分:15)

试试这个:

SELECT 
  t1.id, 
  IFNULL(COUNT(t2.name), 0) AS refNr 
FROM test AS t1
LEFT JOIN test AS t2 ON t1.id = t2.id_user_ref
GROUP BY t1.id;

SQL Fiddle DEmo

这会给你:

| ID | REFNR |
--------------
|  1 |     2 |
|  2 |     1 |
|  3 |     1 |
|  4 |     0 |
|  5 |     0 |

答案 1 :(得分:0)

你能试试吗?

SELECT a.id,
CASE  WHEN b.refNr IS NULL THEN 0
ELSE b.refNr END FROM test a LEFT JOIN
( SELECT id_user_ref, COUNT(name) AS refNr
    FROM test
    WHERE id_user_ref IS NOT NULL
    GROUP BY id_user_ref) b
ON a.id = b.id_user_ref

Sql Demo