SQL - retain ordering based on the query params

前端 未结 7 1922
借酒劲吻你
借酒劲吻你 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条回答
  • 2021-02-10 08:49

    I'm not a Python guy, but here's how I'd do it in PHP and I hope you get the idea.

    1. Build a string like this:

      $str = "('B123', 'B483', 'B100', 'B932', ...)";

      For the above, you can use a for loop or something to build a really long string.

    2. Insert the string in the query like this:

    $MyQuery = "SELECT * FROM orders WHERE order_no IN $str
    ORDER BY $str";
    

    Like I said, this is a PHP example, but I believe you get the idea.

    0 讨论(0)
  • 2021-02-10 08:52

    you can try it will work fine. Check below sql:-

    SELECT * FROM orders WHERE order_no IN ('B123', 'B483', 'B100', 'B932') 
    ORDER BY DECODE(order_no,'B123','1','B483','2','B100','3','B932','4');
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-10 09:00

    Insert the values into a temporary table and join your select to that.

    You can then do a natural order on your temporary table column.

    CREATE GLOBAL TEMPORARY TABLE sort_table (
      value       VARCHAR2(100),
      sort_order  NUMBER
    ) ON COMMIT DELETE ROWS;
    
    INSERT INTO sort_table VALUES ('B123',1);
    INSERT INTO sort_table VALUES ('B483',2);
    ... etc. ...
    
    select * from mytable
    inner join sort_table
    on mytable.mycolumn = sort_table.value
    order by sort_table.sort_order;
    

    To clear the temporary table, just COMMIT.

    0 讨论(0)
  • 2021-02-10 09:00

    If you want to go with DECODE to assign a numerical sort order:

    SELECT ID FROM tbl WHERE ID IN (2,3,1)
    ORDER BY DECODE(ID, 2, 1, 3, 2, 3)
    
    0 讨论(0)
  • 2021-02-10 09:00

    I made an answer here in a more recent question

    https://stackoverflow.com/questions/14234748/preserve-rows-order-in-select-query-as-same-in-statement

    My answer use a pipe row function so it doesn't need to use a temp table like the accepted answer here.

    0 讨论(0)
提交回复
热议问题