MySQL:获取几列的MAX或GREATEST,但具有NULL字段 [英] MySQL: get MAX or GREATEST of several columns, but with NULL fields

查看:1671
本文介绍了MySQL:获取几列的MAX或GREATEST,但具有NULL字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在每个记录的三个不同字段中选择最大日期(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.

这篇关于MySQL:获取几列的MAX或GREATEST,但具有NULL字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆