MySQL:获取多列的 MAX 或 GREATEST,但包含 NULL 字段

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

我试图在每条记录的三个不同字段中选择最大日期 (MySQL)所以,在每一行中,我有 date1、date2 和 date3:date1 总是被填充,date2 和 date3 可以是 NULL 或空GREATEST 语句简单明了,但对 NULL 字段没有影响,因此效果不佳:

I'm trying to select the max date in three different fields in each record (MySQL) So, in each row, I have date1, date2 and date3: date1 is always filled, date2 and date3 can be NULL or empty The GREATEST statement is simple and concise but has no effects on NULL fields, so this doesn't work well:

SELECT id, GREATEST(date1, date2, date3) as datemax FROM mytable

我还尝试了更复杂的解决方案,例如:

I tried also more complex solutions like this:

SELECT
    CASE
        WHEN date1 >= date2 AND date1 >= date3 THEN date1
        WHEN date2 >= date1 AND date2 >= date3 THEN date2
        WHEN date3 >= date1 AND date3 >= date2 THEN date3
        ELSE                                        date1
    END AS MostRecentDate

同样的问题:NULL 值是返回正确记录的一个大问题

Same problem here: NULL values are a GREAT problem in returning the right records

请问,你有解决办法吗?提前致谢....

Please, have you got a solution? Thanks in advance....

推荐答案

使用COALESCE

SELECT id, 
   GREATEST(date1, 
     COALESCE(date2, 0),
     COALESCE(date3, 0)) as datemax 
FROM mytable

更新:这个答案以前使用了 IFNULL ,它确实有效,但正如 Mike Chamberlain 在评论中指出的那样,COALESCE 实际上是首选方法.

Update: This answer previously used IFNULL which does work, but as Mike Chamberlain pointed out in the comments, COALESCE is actually the preferred method.

相关文章