Return 零而不是子查询中的 NULL

Return zero instead NULL in subquery

我需要计算每位作者的 post 篇。我正在使用子查询来计算它们。 但是作者那里没有post,结果是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

我该如何解决这个问题?

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

我想你可以通过将内部 select 放在 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,第二个参数就会被传递。如果不是,那么将传递第一个参数的结果。

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