简体   繁体   English

在子查询中返回零而不是NULL

[英]Return zero instead NULL in subquery

I need to count the posts for each author. 我需要计算每位作者的职位。 I'm using subquery for count them. 我正在使用子查询来计数它们。 But where an author has not post, the result is NULL, but I wish 0. 但是在没有作者的地方,结果为NULL,但我希望为0。

SELECT id, name,
    (SELECT COUNT(id)
    FROM posts
    WHERE post.author = authors.id
    GROUP BY author) as post_num
FROM authors
ORDER BY post_num DESC

How can I solve the problem? 我该如何解决这个问题?

Use COALESCE : 使用COALESCE

SELECT id, name,
       COALESCE((SELECT COUNT(id) 
                 FROM posts 
                 WHERE post.author = authors.id 
                 GROUP BY author), 0) as post_num
FROM authors 
ORDER BY post_num DESC

I think you can solve this by putting the inner select in an IsNull function. 我认为您可以通过将内部选择放在IsNull函数中来解决此问题。

Select id, name,
IsNull(SELECT COUNT(id) FROM posts
       WHERE post.author = authors.id
       GROUP BY author, 0) as post_num
FROM authors
ORDER BY post_num DESC

MSDN link MSDN链接

Basically if the first argument of the IsNull function is NULL, the second argument will be passed. 基本上,如果IsNull函数的第一个参数为NULL,则将传递第二个参数。 If not, then the result of the firt argument will be passed. 如果没有,那么firt参数的结果将被传递。

coalesce solve your question, but probably you will get better performance if you use a LEFT JOIN so consider try it. coalesce解决您的问题,但是如果您使用LEFT JOIN ,可能会获得更好的性能,因此请考虑尝试一下。

 SELECT a.id, a.name, count(post.author) as post_num
 FROM authors a
 LEFT JOIN post p 
        ON a.id = p.author
 GROUP BY a.id

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

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