MySQL COUNT IF不起作用并给出全0

时间:2019-10-05 03:19:51

标签: mysql sql count left-join

通过使用左联接,我尝试计算现有购买的形状数量(如果没有购买,则为0)。我也按形状类型将它们分组。但是我得到的结果都是0。

表格形状:

id  shape     colour
1   circle    red
2   rectangle blue
3   triangle  green
4   star      yellow
5   cross     purple
6   moon      orange

表格shape_purchase:

id  price
3   3.24
2   1.95
3   5.42
4   6.32
5   4.21
1   7.45
3   5.97
3   4.31
1   6.32
4   7.82

SQL: SELECT shapes.shape, COUNT(IF(shape_purchase.price != NULL, 1, NULL)) FROM shapes LEFT JOIN shape_purchase ON shapes.id = shape_purchase.id GROUP BY shapes.id <-这里怎么了?

结果:

shape      COUNT(IF(shape_purchase.price != NULL, 1, NULL))
circle     0
rectangle  0
triangle   0
star       0
cross      0
moon       0

我叫shape_purchase.price的事实有问题吗?还是左联接使事情变得更复杂?

仅供参考,SELECT * FROM shapes LEFT JOIN shape_purchase ON shapes.id = shape_purchase.id如下:

id  shape      colour  id    price
3   triangle   green   3     3.24
2   rectangle  blue    2     1.95
3   triangle   green   3     5.42
4   star       yellow  4     6.32
5   cross      purple  5     4.21
1   circle     red     1     7.45
3   triangle   green   3     5.97
3   triangle   green   3     4.31
1   circle     red     1     6.32
4   star       yellow  4     7.82
6   moon       orange  NULL  NULL

1 个答案:

答案 0 :(得分:1)

几乎与NULL的任何比较都是NULL -被视为错误。包括不平等。这就是SQL具有IS NULLIS NOT NULL的原因。

但是,我建议您将代码编写为:

SELECT s.shape, COUNT(sp.price)
FROM shapes s LEFT JOIN
     shape_purchase sp
     ON s.id = sp.id
GROUP BY s.id;

COUNT(<expression>)计算非NULL的值。不需要条件逻辑。