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 ?

2
  • NULL values can do weird things with comparisons. See what happens if you do something like GROUP BY IFNULL(referer_id, -1). Commented May 4, 2016 at 0:32
  • Same thing, the NULL is still 0 Commented May 4, 2016 at 0:42

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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

1 Comment

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.

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.