我有以下查询(通过 PHP 执行)。如果结果为 NULL 并且未显示,如何使其显示零。
select count(schicht) as front_lcfruh,
kw,
datum
from dienstplan
left join codes on dienstplan.schicht = codes.lcfruh
left join personal on personal.perso_id = dienstplan.perso_id
where codes.lcfruh != ''
and personal.status = 'rezeption'
and dienstplan.kw = '$kw'
group by dienstplan.datum
最佳答案
我不完全确定我理解这个问题,但我认为你想要这个:
select <b><i>count(codes.lcfruh)</i></b> as front_lcfruh,
dienstplan.kw,
dienstplan.datum
from dienstplan
left join codes on dienstplan.schicht = codes.lcfruh and codes.lcfruh <> ''
left join personal on personal.perso_id = dienstplan.perso_id
and personal.status = 'rezeption'
and dienstplan.kw = $kw
group by dienstplan.datum, dienstplan.kw
如果schicht
来自dienstplan
,那么总会有一行(因为那是驱动表)。如果我理解正确的话,如果没有找到匹配的行,您需要 0
。因此,您需要计算已连接表的数量。
编辑:
条件 wherecodes.lcfruh != ''
将外部联接转回内部联接,因为任何“外部”行的 lcfruh 都将为 NULL,并且与 NULL 的任何比较都会产生“未知”,因此这些行从最终结果中删除。如果您想要排除 codes
表中 lcfruh
包含空字符串的行,则需要将该条件移至 JOIN 子句中(参见上文)。
还有两件事:习惯在具有多个表的查询中为列添加前缀。这可以避免歧义,并使查询在变化时更加稳定。您还应该了解数字文字和字符串文字之间的区别 1
是数字 '1'
是字符串。在需要数字的地方使用字符串文字是一个坏习惯。 MySQL 非常宽容,因为它总是尝试“以某种方式”工作,但如果您曾经使用过其他 DBMS,您可能会遇到您不理解的错误。
此外,您对 group by
的使用是错误的,会导致返回“随机”值。请参阅这些博客文章以了解原因:
- http://rpbouman.blogspot.de/2007/05/debunking-group-by-myths.html
- http://www.mysqlperformanceblog.com/2006/09/06/wrong-group-by-makes-your-queries-fragile/
所有其他 DBMS 都会以现在的方式拒绝您的查询(如果您打开更符合 ANSI 的模式,MySQL 也会拒绝您的查询)
关于mysql - 如果 sql 计数为 NULL,则显示零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18991803/