【问题标题】:ORDER BY Clause with IF Statment带有 IF 语句的 ORDER BY 子句
【发布时间】:2021-01-21 01:44:52
【问题描述】:

我正在努力使用带有 If 语句的 Order by 子句而没有 If 语句它工作正常。我的test 表中有两个关键点,即int 类型和timestamp 类型的日期。我正在添加示例数据以供参考

Table Name - test

    id  points    date
    ------------------------
    1   90        2019-12-14 09:01:10
    2   10        2019-12-15 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    5   606       2019-12-9 09:01:10

所以我的查询

SELECT id, points, date FROM test order by points desc

返回

    id  points    date
    ------------------------
    5   606       2019-12-9 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    1   90        2019-12-14 09:01:10
    2   10        2019-12-15 09:01:10

这是预期的结果,但如果我尝试在 If 子句中添加 points,那么它会按字母顺序对点进行排序

查询

SELECT id, points, date FROM test order by IF(TRUE, points, date) desc

返回

    id  points    date
    ------------------------
    1   90        2019-12-14 09:01:10
    5   606       2019-12-9 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    2   10        2019-12-15 09:01:10

我怎样才能按数字降序获得结果。

预期结果

    id  points    date
    ------------------------
    5   606       2019-12-9 09:01:10
    3   200       2019-12-16 09:01:10
    4   120       2019-12-6 09:01:10
    1   90        2019-12-14 09:01:10
    2   10        2019-12-15 09:01:10

注意:我使用的是 MYSQL 8.0.21

【问题讨论】:

  • IF 语句只能用于复合语句(过程、函数、触发器等)。你的意思是 IF 函数。在您的情况下返回字符串类型值。
  • @Akina,Yaa,我的意思是如果函数
  • 请更清楚地制定所需的排序标准。
  • 请向我们展示您想要的结果。
  • @GMB 我已经在我的问题中添加了所需的结果。我的第一个查询返回所需的结果

标签: mysql sql sql-order-by case mysql-8.0


【解决方案1】:

来自cmets:

我想根据用户输入对我的结果进行排序,用户可以选择,他想按点或日期字段对结果进行排序

这两列具有不同的数据类型,因此您需要两种不同级别的排序。假设用户输入以参数:order_col 的形式给出,它可能取值“points”或“date”:

order by 
    case when :order_col = 'points' then points end desc,
    case when :order_col = 'date' then date end desc

另一种方法是将日期转换为数字,例如使用unix_timestamp():然后数据类型是一致的,单级排序就足够了:

order by case :order_col
    when 'points' then points
    when 'date' then unix_timestamp(date)
end desc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    相关资源
    最近更新 更多