MySQL容易犯的一些小错误:

1.COUNT(expr)
Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value.
COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain NULL values.

count(*):不忽略NULL值,有几行算几行;
count(num):如果字段值为NULL,该行忽略不统计;
因此,针对某个字段进行统计时,如果该字段可能为NULL就要注意了,这可能不是你想要的结果。

2.SUM([DISTINCT] expr)
If there are no matching rows, SUM() returns NULL.

SUM函数,会忽略NULL值,对非NULL值求和。
但需要注意的是,如果没查到数据,或字段全为NULL,则SUM函数返回NULL。
为避免出现空指针,一般我们希望的是返回0。解决方法如下:
select coalesce(sum(num),0)...,select ifnull(sum(num),0)...

If there are no matching rows:
AVG() returns NULL.
COUNT() returns 0.
COUNT(DISTINCT) returns 0.
MAX() returns NULL.
MIN() returns NULL.
SUM() returns NULL.

dev.mysql.com
展开
评论