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

时间:2016-02-08 22:15:43

标签: mysql count subquery

我需要计算每位作者的帖子。我正在使用子查询来计算它们。 但是如果作者没有发帖,则结果为NULL,但我希望为0。

YouSegmentedViewController

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

使用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

答案 1 :(得分:1)

我认为你可以通过将内部选择放在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

基本上,如果IsNull函数的第一个参数为NULL,则传递第二个参数。如果没有,那么将传递firt参数的结果。

答案 2 :(得分:1)

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