SQL - retain ordering based on the query params

前端 未结 7 2029
借酒劲吻你
借酒劲吻你 2021-02-10 08:34

I\'m trying to perform a SELECT with an IN clause and I would like to be able to have the results returned in the same order as the elements in my list

7条回答
  •  萌比男神i
    2021-02-10 08:59

    I don't know if there is an elegant (or short) solution for this.

    If you can build the query dynamically, the following should work:

    WITH numbers AS (
       SELECT 1 as sort_order, 'B123' as order_no FROM DUAL
       union all
       SELECT 2 as sort_order, 'B483' as order_no FROM DUAL
       union all
       SELECT 2 as sort_order, 'B100' as order_no FROM DUAL
       union all
       SELECT 2 as sort_order, 'B932' as order_no FROM DUAL
    )
    SELECT orders.*
    FROM numbers  
      LEFT JOIN orders ON orders.ord_no = numbers.ord_no
    ORDER BY numbers.sort_order
    

提交回复
热议问题