MySQL按两个日期字段取较大值排序的正确SQL语句咨询
Problem Statement
I'm working on a MySQL query that needs to sort records based on specific rules involving date_created and date_updated fields. Here's the sample data:
| 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 |
Sorting Rules
- If
date_updatedis null, usedate_createdfor sorting. - If
date_updated > date_created(the normal case), usedate_updatedfor sorting. - If two records have the same sorting value (one using
date_createdbecausedate_updatedis null, the other usingdate_updated), the record with nulldate_updatedshould come first.
Expected Result
| 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 |
I tried this SQL query, but it doesn't meet rule 2:
SELECT * FROM table t ORDER BY CASE WHEN t.date_updated IS NOT NULL AND t.date_updated > t.date_created THEN t.date_created ELSE t.date_updated END DESC
What's the correct MySQL query to satisfy all three rules?
Solution
Got it, let's fix this sorting issue step by step. First, the problem with your original query is that your CASE statement had it backwards: when date_updated is valid and newer than date_created, you were using date_created for sorting instead of date_updated—that's why rule 2 wasn't being met.
To cover all three rules, we need two parts in our ORDER BY clause:
- First, select the correct date to sort by (following rules 1 and 2) and sort in descending order.
- Second, add a priority flag to ensure records with null
date_updatedcome first when their sorting dates match (rule 3).
Here's the corrected query:
SELECT * FROM `table` t ORDER BY -- Rule 1 & 2: Pick the right date for sorting CASE WHEN t.date_updated IS NOT NULL AND t.date_updated > t.date_created THEN t.date_updated ELSE t.date_created END DESC, -- Rule 3: Prioritize records with null date_updated when sorting dates are equal CASE WHEN t.date_updated IS NULL THEN 0 ELSE 1 END ASC;
How This Works
- First Sort Field: The
CASEnow correctly usesdate_updatedfor the normal scenario (rule 2). For nulldate_updatedor cases wheredate_updatedisn't newer thandate_created, it falls back todate_created(rule 1). We sort this field descending to get the newest records at the top. - Second Sort Field: This
CASEassigns a lower value (0) to records with nulldate_updatedand 1 to others. Sorting this ascending ensures that when two records have the same sorting date, the one with a nulldate_updatedtakes precedence (rule 3).
Running this query against your sample data will produce exactly the expected result you listed.
内容的提问来源于stack exchange,提问作者Lawrence Colombo

