Ordering by the order of values in a SQL IN() clause

前端 未结 13 785
旧巷少年郎
旧巷少年郎 2020-11-22 04:12

I am wondering if there is away (possibly a better way) to order by the order of the values in an IN() clause.

The problem is that I have 2 queries, one that gets al

13条回答
  •  北海茫月
    2020-11-22 04:56

    If you want to do arbitrary sorting on a query using values inputted by the query in MS SQL Server 2008+, it can be done by creating a table on the fly and doing a join like so (using nomenclature from OP).

    SELECT table1.name, table1.description ... 
    FROM (VALUES (id1,1), (id2,2), (id3,3) ...) AS orderTbl(orderKey, orderIdx) 
    LEFT JOIN table1 ON orderTbl.orderKey=table1.id
    ORDER BY orderTbl.orderIdx
    

    If you replace the VALUES statement with something else that does the same thing, but in ANSI SQL, then this should work on any SQL database.

    Note: The second column in the created table (orderTbl.orderIdx) is necessary when querying record sets larger than 100 or so. I originally didn't have an orderIdx column, but found that with result sets larger than 100 I had to explicitly sort by that column; in SQL Server Express 2014 anyways.

提交回复
热议问题