草庐IT

sql - MySQL Order by multiple column combined (not order by field1 asc, field2 asc)

coder 2023-10-04 原文

这似乎是一个典型的问题,但它是不同的。

我有一个带有 id 和 3 个时间戳字段的表(简单来说)。最初所有 3 个字段都是空的,并且它们被值填充。行的例子是:

id time1      time2      time3
1  1259625661 1259643563 null
2   null      1259621231 null
3  1259625889 null       1259644511
4   null      1259621231 null
5   null      null       1259644511
6   null      1259621231 null
7  1259625889 null       null

我需要的是获取按最近时间戳排序的 ID 列表(忽略时间 1、时间 2 或时间 3)。 按 time1 desc、time2 desc、time3 desc 排序 给我一个错误的列表,因为它首先对所有 time1 字段进行排序,然后是第二个,依此类推...

预期结果是一个 id 列表。

这可以在 MySQL 中通过单个查询完成吗?谢谢

最佳答案

SELECT  *
FROM    mytable
ORDER BY
        GREATEST(
        COALESCE(time1, 0),
        COALESCE(time2, 0),
        COALESCE(time3, 0)
        ) DESC

关于sql - MySQL Order by multiple column combined (not order by field1 asc, field2 asc),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826820/

有关sql - MySQL Order by multiple column combined (not order by field1 asc, field2 asc)的更多相关文章

随机推荐