1

Let's say I have a users table with two column, id and referer_id

enter image description here

If the user was refered by someone else, his referrer will be in referer_id. If he signed up by himself then the referer_id will be NULL

I want to count how many referred users a user has.

I have a query like this

SELECT `referer_id`,count(`referer_id`) FROM `users`
GROUP BY `referer_id`

enter image description here

As you can see the NULL count is 0 , but I have a lot of users who was not refered by anybody. How can I solve this ?

rmths01
  • 89
  • 1
  • 10

3 Answers3

1

I don't like this, I think there's a more elegant solution out there, but it works and may help you find that better solution.

select 
  t1.id,
  ifnull(t3.ct, 0)
  from 
    temp t1
    left join 
      (select 
         t2.referer_id,
         count(t2.referer_id) as ct
         from temp t2
         group by t2.referer_id) t3
  on t1.id = t3.referer_id;

With a little more thought, here's an option that avoids the subselect:

select t1.id, ifnull(count(t2.referer_id), 0)
from temp t1
left join temp t2 on t1.id = t2.referer_id
group by t1.id;
ghenghy
  • 361
  • 1
  • 5
1

Even though I can't explain what reason caused this issue, I figured it out with another solution, like this;)

SELECT `referer_id`,
       if(`referer_id` is null, @num := @num + 1, count(`referer_id`)) as referer_id_cnt
FROM `users`, (select @num := 0) tmp
GROUP BY `referer_id`

Hmm, what I've wrote above is definitely not a proper answer. Actually this will help you.

SELECT `referer_id`,count(1) FROM `users`
GROUP BY `referer_id`

And take a look of this link How to count NULL values in MySQL?

Community
  • 1
  • 1
Blank
  • 12,308
  • 1
  • 14
  • 32
0
SELECT `referer_id`,count(NVL(`referer_id`,0)) 
FROM `users`
GROUP BY `referer_id`
Adesh
  • 34
  • 4
  • Unfortunately, his question pertains to mysql, which has no NVL function. ifnull is the mysql equivalent. However, even if you do this query w/ ifnull, it still doesn't return results for those that have no referers, which is what the OP wants. – ghenghy May 04 '16 at 18:49