为NULL时如何用MAX函数设置0?

2022-01-06 00:00:00 max null zero mysql

我想了解如何使用 MAX 函数在属性为 NULL 时设置属性的 0 值.例如:

I would like to understand how to set 0 value of the attribute when it is NULL with MAX function. For example:

Name columns:
number - date

Values:
10 - 2012-04-04
11 - 2012-04-04
12 - 2012-04-04
13 - 2012-04-15
14 - 2012-06-21
 1 - 2013-07-04

Number 是增量字段,但它在新年到来时将自己设置为 1.但结果:

Number is incremental field, but it has set itself 1 when new year has come. But result of:

SELECT (MAX(number)+1) number WHERE date LIKE "2014%" 

是 NULL 而不是 1 因为 MAX(number) 是 NULL 而不是 0

is NULL and not 1 because MAX(number) is NULL and not 0

推荐答案

好吧,因为没有像 2014 年这样的日期,所以您会期望 null,因为没有的最大值实际上是没有任何意义的.

Well, as there is no date like 2014, you would expect null, because the maximum of nothing is actually not anyting.

但是这样做:

COALESCE(MAX(number),0)

这意味着:从下一个列表中获取第一个非空的东西,所以如果你的 max 为空,它会给你 0

Which means: get the first non-null thing from the next list, so if your max is null, it'll give you 0

相关文章