【问题标题】:Ordering columns in sqlsql中的列排序
【发布时间】:2021-01-31 00:39:46
【问题描述】:

我在数据库中有数据


德国
印度
美国
中国
日本
非洲


我想要一个 sql 查询结果:


印度(印度为第一行)
非洲(所有其他按字母顺序排列)
日本
美国
中国(中国为最后一排)


【问题讨论】:

    标签: mysql sql sql-order-by sql-query-store


    【解决方案1】:

    您可以使用多个级别的排序:

    order by col = 'India' desc, col = 'China', col
    

    基本原理:在 MySQL 中,如果满足条件,表达式 col = <val> 返回 1,否则返回 0。所以col = 'India' desc 将印度放在首位,而col = 'China' 将中国放在最后。然后通过对国家/地区名称进行常规排序来打破平局。

    【讨论】:

      【解决方案2】:

      在 MySQL 中,你可以这样做:

      order by (col = 'India') desc,
               (col = 'China') asc,
               col asc
      

      或者使用case 表达式:

      order by (case when col = 'India' then 1
                     when col = 'China' then 3
                     else 2
                end)
               col
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-25
        • 2011-01-04
        • 1970-01-01
        • 2012-09-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多