带计数返回空行的mysql,MySQL-选择COUNT并返回NULL行

本文探讨了在SQL查询中,当期望返回0行结果时,使用内连接(INNER JOIN)与左连接(LEFT JOIN)的差异。通过示例,解释了在特定条件下,如何正确使用LEFT JOIN结合COUNT函数进行计数操作,以避免返回空行。同时,强调了在使用聚合函数时配合GROUP BY子句的重要性。
摘要由CSDN通过智能技术生成

This works

SELECT DISTINCT b.b_id

FROM b INNER JOIN c

ON b.b_id=c.b_id

WHERE c.active='yes' AND b.featured='no'

When the results should be 0 rows returned, this returns a null row with count = 0

SELECT DISTINCT b.b_id, COUNT(c.c_id) AS count

FROM b INNER JOIN c

ON b.b_id=c.b_id

WHERE c.active='yes' AND b.featured='no'

Am I doing something wrong?

解决方案

I think you want a left join instead of an inner join since you want to return a count of 0 instead of a missing row when there is no matching c record for a given b record.

Also, you should include a group by when using an aggregate function, such as count.

SELECT

b.b_id,

COUNT(DISTINCT c.c_id) AS count

FROM

b

LEFT JOIN c

ON b.b_id=c.b_id

AND c.active='yes'

WHERE b.featured='no'

GROUP BY b.b_id

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值