12

I have this table structure with data:

INSERT INTO `test` (`id`, `email`, `id_user_ref`, `name`) VALUES
(1, '[email protected]', NULL, 'Mike'),
(2, '[email protected]', '1', 'Jhonny'),
(3, '[email protected]', '1', 'Michael'),
(4, '[email protected]', '2', 'Jorhe'),
(5, '[email protected]', '3', 'Mia');

I need to count the id_user_ref for all users with this query:

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

This works but the problem is that i need to display all results even if the count result is 0.

I tried several left joins with the same table but without any success.

The output should be:

id  refNr
1    2
2    1
3    1
4    0
5    0
4
  • you want to count how many users mike invited? then you will run into a inner join from the table to itself :-) Commented Apr 2, 2013 at 7:13
  • What is the desired output you want to get from this query? Commented Apr 2, 2013 at 7:15
  • i need to know how for every person how many persons have their id ref including 0 Commented Apr 2, 2013 at 7:17
  • i added the expected result to the question Commented Apr 2, 2013 at 7:19

2 Answers 2

23

Try this:

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

This will give you:

| ID | REFNR |
--------------
|  1 |     2 |
|  2 |     1 |
|  3 |     1 |
|  4 |     0 |
|  5 |     0 |
Sign up to request clarification or add additional context in comments.

3 Comments

ON t1.id = t2.id_user_ref doesnt makes any sense to me. These columns arnt the same!?
@C4ud3x - The column id is the id of the user, the column id_user_ref is a reference id to the id column, the user is looking for a way to get the count of the referenced ids by each id with 0 for those who don't have a reference. So the way to do this is to LEFT JOIN the same table, like what I did in my query.
This one works for me, even if I've no idea what's going on.... I think I need to learn more about LEFT JOIN...
1

Can you try this ?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.