我今天遇到了一个问题,正在调试一些代码:给定以下MySQL数据片段:
╔════╦═════════════════════╦═════════════════════╗
║ id ║ date_created ║ date_updated ║
╠════╬═════════════════════╬═════════════════════╣
║ 1 ║ 2015-12-07 15:04:21 ║ 2016-06-06 10:59:25 ║
╠════╬═════════════════════╬═════════════════════╣
║ 2 ║ 2016-06-06 10:59:25 ║ 2016-09-09 09:44:58 ║
╠════╬═════════════════════╬═════════════════════╣
║ 3 ║ 2016-09-09 09:44:59 ║ 2017-11-30 11:36:37 ║
╠════╬═════════════════════╬═════════════════════╣
║ 4 ║ 2017-11-30 11:36:37 ║ null ║
╚════╩═════════════════════╩═════════════════════╝我需要对这些日期进行相应的排序:
date_updated是null,那么使用它的date_createddate_updated > date_created,那么使用它的date_updated (尽管应该总是这样)date_created,B的date_updated不是null,这两个值相等,那么A的顺序应该大于B。因此,我的预期结果应该是:
╔════╦═════════════════════╦═════════════════════╗
║ id ║ date_created ║ date_updated ║
╠════╬═════════════════════╬═════════════════════╣
║ 4 ║ 2017-11-30 11:36:37 ║ null ║
╠════╬═════════════════════╬═════════════════════╣
║ 3 ║ 2016-09-09 09:44:59 ║ 2017-11-30 11:36:37 ║
╠════╬═════════════════════╬═════════════════════╣
║ 2 ║ 2016-06-06 10:59:25 ║ 2016-09-09 09:44:58 ║
╠════╬═════════════════════╬═════════════════════╣
║ 1 ║ 2015-12-07 15:04:21 ║ 2016-06-06 10:59:25 ║
╚════╩═════════════════════╩═════════════════════╝我尝试了以下查询:
SELECT * FROM table t
ORDER BY
CASE
WHEN t.date_updated IS NOT NULL AND t.date_updated > t.dated_created
THEN t.date_created
ELSE t.date_updated
END
DESC然而,这并没有按照第2点正确排序。这里正确的MySQL语句是什么?
发布于 2018-01-10 12:05:23
date_updated应优先于date_created。为此使用COALESCE:
SELECT *
FROM mytable
ORDER BY COALESCE(date_updated, date_created) DESC;发布于 2018-01-10 12:19:11
案例陈述的逻辑是不正确的。错误地,您替换了t.date_updated和t.date_created (下面的SQL查询中的第5行和第6行)。
试试这个
SELECT * FROM table t
ORDER BY
CASE
WHEN t.date_updated IS NOT NULL AND t.date_updated > t.dated_created
THEN t.date_updated
ELSE t.date_created
END
DESChttps://stackoverflow.com/questions/48187037
复制相似问题