【问题标题】:how to order by <= 7 desc then by > 7 asc?如何按 <= 7 desc 然后按 > 7 asc 订购?
【发布时间】:2020-08-31 16:57:01
【问题描述】:

在我的桌子上https://www.db-fiddle.com/f/4yPorU6k3SjQ5nmhgi1wGo/0

我使用查询

SELECT id
FROM test
ORDER BY id <= 7 DESC, id DESC

我想订购从 7 到较小的所有东西,然后按较小的顺序订购其他所有东西

我的查询给我

| id  |
| --- |
| 6   |
| 3   |
| 2   |
| 1   |
| 65  |
| 35  |
| 34  |
| 33  |
| 12  |
| 11  |
| 11  |
| 10  |

但我想给我

| id  |
| --- |
| 6   |
| 3   |
| 2   |
| 1   |
| 10  |
| 11  |
| 11  |
| 12  |
| 33  |
| 34  |
| 35  |
| 65  |

【问题讨论】:

    标签: mysql sql database select sql-order-by


    【解决方案1】:

    考虑条件排序,如下所示:

    select id
    from test
    order by
        case when id <= 7 then id end desc,
        id
    

    Demo on DB Fiddle

    |编号 | | -: | | 6 | | 3 | | 2 | | 1 | | 10 | | 11 | | 11 | | 12 | | 33 | | 34 | | 35 | | 65 |

    【讨论】:

      【解决方案2】:

      我想你想要:

      SELECT id
      FROM test
      ORDER BY id <= 7 DESC, 
               (CASE WHEN id <= 7 THEN id END) DESC,
               id ASC
      

      【讨论】:

        猜你喜欢
        • 2013-06-30
        • 2023-04-04
        • 2018-09-29
        • 1970-01-01
        • 2018-09-09
        • 2014-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多