简体   繁体   English

MySQL选择返回错误的NULL值与COUNT

[英]MySQL Select return wrong NULL value with COUNT

Let's say I have a users table with two column, id and referer_id 假设我有一个users表,其中有两列,即idreferer_id

在此处输入图片说明

If the user was refered by someone else, his referrer will be in referer_id . 如果该用户被其他人推荐,则他的推荐人将位于referer_id If he signed up by himself then the referer_id will be NULL 如果他自己签名,则referer_id将为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`

在此处输入图片说明

As you can see the NULL count is 0 , but I have a lot of users who was not refered by anybody. 如您所见,NULL计数为0,但是我有很多用户没有被任何人引用。 How can I solve this ? 我该如何解决?

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;

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? 看看这个链接如何在MySQL中计算NULL值?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM