繁体   English   中英

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

[英]Return zero instead NULL in subquery

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

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

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

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