Order by `updated_at` and `created_at` even if they are NULL

霸气de小男生 提交于 2020-01-07 04:44:04

问题


I have the following table:

CREATE TABLE `entries` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

I want to sort the entries by both updated_at and created_at.

But either of them could be NULL.

My query:

SELECT *
FROM `entries`
ORDER BY `updated_at` DESC, `created_at` DESC, `id` DESC

But this will put every entry which has not been updated at the bottom of the results.

Basically I need them to be sorted by the last date available. And if there is none available to be sorted by id.


回答1:


I believe what you want is:

ORDER BY coalesce(updated_at, created_at) DESC, id DESC

This orders by either the updated date (if available) or the created date (if it is not available). Then it orders by id descending.




回答2:


You can use a CASE statement.

SELECT *
FROM `entries`
ORDER BY CASE WHEN `updated_at` IS NOT NULL then `updated_at` WHEN `created_at` IS NOT NULL then `created_at` ELSE `id` END DESC



回答3:


Perhaps try COALESCE:

SELECT *
FROM `entries`
ORDER BY COALESCE(updated_at, created_at, id) DESC

This isn't necessarily exactly what you asked for, but it's likely getting into the direction you want. If it's not right, can you post an example of what you want?




回答4:


I don't exactly understand what you want but you can try this:

SELECT *
FROM `entries`
ORDER BY IFNULL(`updated_at`,`created_at`) DESC, `id` DESC

If one of those dates is available, the results will be sorted by the date. If no date is available, the result will be sorted by id.

Note: IFNULL is not necessarily available on your DBMS but you can find an equivalent.



来源:https://stackoverflow.com/questions/15501293/order-by-updated-at-and-created-at-even-if-they-are-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!