【问题标题】:MySQL Order by multiple column combined (not order by field1 asc, field2 asc)MySQL 按多列组合排序(不是按 field1 asc、field2 asc 排序)
【发布时间】:2009-12-01 15:12:54
【问题描述】:

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

我有一个带有 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 列表(忽略它是否在 time1、time2 或 time3 中)。 按 time1 desc、time2 desc、time3 desc 排序会给我一个错误的列表,因为它首先对所有 time1 字段进行排序,然后是第二个,等等...

预期结果是 id 的列表。

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

【问题讨论】:

    标签: sql mysql sql-order-by


    【解决方案1】:
    SELECT  *
    FROM    mytable
    ORDER BY
            GREATEST(
            COALESCE(time1, 0),
            COALESCE(time2, 0),
            COALESCE(time3, 0)
            ) DESC
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多