Keep order from 'IN' clause

后端 未结 5 1423
花落未央
花落未央 2020-12-11 00:23

Is it possible to keep order from a \'IN\' conditional clause?

I found this question on SO but in his example the OP have already a sorted \'IN\' clause.

My

5条回答
  •  醉酒成梦
    2020-12-11 00:58

    There will be no reliable ordering unless you use an ORDER BY clause ..

    SELECT SomeField,OtherField
    FROM TestResult 
    WHERE TestResult.SomeField IN (45,2,445,12,789)
    order by case TestResult.SomeField
             when 45 then 1
             when 2  then 2
             when 445 then 3
             ...
             end
    

    You could split the query into 5 queries union all'd together though ...

    SELECT SomeField,OtherField
    FROM TestResult 
    WHERE TestResult.SomeField = 4
    union all
    SELECT SomeField,OtherField
    FROM TestResult 
    WHERE TestResult.SomeField = 2
    union all
    ...
    

    I'd trust the former method more, and it would probably perform much better.

提交回复
热议问题