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

MySQL: get MAX or GREATEST of several columns, but with NULL fields(MySQL:获取多列的 MAX 或 GREATEST,但包含 NULL 字段)
本文介绍了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 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)