在下面的查询中,如果查询不返回任何结果,则将either子句中的比较操作符从'=‘更改为'<’,这样就可以返回(所有NULL中的)1行或不返回任何行。
有人能解释一下为什么这种行为会被证明吗?理想情况下,我希望第一个查询返回0行,但如果不将其包装在另一个查询中以排除NULL,那就更好了。
查询:
SELECT `templates`.*
FROM `templates`
INNER JOIN `items` ON `items`.`template_id` = `templates`.`id`
HAVING COUNT(items.id) = 0结果:
NULL,NULL,NULL...
(1 row(s) returned)与以下方面相比:
查询:
SELECT `templates`.*
FROM `templates`
INNER JOIN `items` ON `items`.`template_id` = `templates`.`id`
HAVING COUNT(items.id) < 0结果:
(0 row(s) returned)但是,HAVING COUNT(items.id) < 1的这种变化还会返回NULL行:
查询:
SELECT `templates`.*
FROM `templates`
INNER JOIN `items` ON `items`.`template_id` = `templates`.`id`
HAVING COUNT(items.id) < 1结果:
NULL,NULL,NULL...
(1 row(s) returned)发布于 2015-07-02 05:24:29
简单地说,count()函数永远不会返回负值。你的条件是having count(items.id) < 0,意思是having 0 < 0,永远是false。但是having count(items.id)=0可以是真手段,也可以是count(items.id)<1是真,意思是0=0或0<1是真。
mysql> select 1 from test having count(id)=0;
+---+
| 1 |
+---+
| 1 |
+---+
1 row in set (0.29 sec)
mysql> select 1 from test having count(id)<0;
Empty set (0.00 sec)https://stackoverflow.com/questions/31176073
复制相似问题