Returning query results in predefined order

前端 未结 11 1009
温柔的废话
温柔的废话 2020-11-29 06:01

Is it possible to do a SELECT statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 and returning them in that order, based on

相关标签:
11条回答
  • 2020-11-29 06:41

    Best I can think of is adding a second Column orderColumn:

    7 1
    2 2
    5 3
    9 4 
    8 5
    

    And then just do a ORDER BY orderColumn

    0 讨论(0)
  • 2020-11-29 06:43

    Could you include a case expression that maps your IDs 7,2,5,... to the ordinals 1,2,3,... and then order by that expression?

    0 讨论(0)
  • 2020-11-29 06:50

    Your best bet is:

    ORDER BY FIELD(ID,7,2,4,5,8) 
    

    ...but it's still ugly.

    0 讨论(0)
  • 2020-11-29 06:54

    This works in Oracle. Can you do something similar in MySql?

    SELECT ID_FIELD
    FROM SOME_TABLE
    WHERE ID_FIELD IN(11,10,14,12,13)
    ORDER BY
      CASE WHEN ID_FIELD = 11 THEN 0
           WHEN ID_FIELD = 10 THEN 1
           WHEN ID_FIELD = 14 THEN 2
           WHEN ID_FIELD = 12 THEN 3
           WHEN ID_FIELD = 13 THEN 4
      END
    
    0 讨论(0)
  • 2020-11-29 06:55

    All ordering is done by the ORDER BY keywords, you can only however sort ascending and descending. If you are using a language such as PHP you can then sort them accordingly using some code but I do not believe it is possible with MySQL alone.

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