11

我有这个带有数据的表结构:

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
4

2 回答 2

21

试试这个:

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 演示

这会给你:

| ID | REFNR |
--------------
|  1 |     2 |
|  2 |     1 |
|  3 |     1 |
|  4 |     0 |
|  5 |     0 |
于 2013-04-02T07:18:35.330 回答
1

你能试试这个吗?

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 演示

于 2013-04-02T07:30:39.777 回答