mysql custom sort

前端 未结 4 1570
遥遥无期
遥遥无期 2020-12-01 09:32

I have a query like this: SELECT * FROM table WHERE id IN (2,4,1,5,3);

However, when I print it out, it\'s automatically sorted 1,2,3,4,5. How can we ma

4条回答
  •  有刺的猬
    2020-12-01 10:17

    (I would have written this as a comment on Michel Tobon's answer, but don't have the reputation, sorry :-)

    "And it worked... why? Beats me, but it just did; try it as well."

    The reason that works is because your expression "code!='USA'" is producing a boolean result, which in SQL is represented as a 1 or 0. So, the expression "code='USA' produces a 1 for every record that matches that criterion, and a 0 for every record that does not. Because 1 is later than 0 in an ascending sort (the default), matching records will sort later than unmatching ones. Thus negating that expression producing the opposite effect.

    Another (possibly clearer) way of producing the same result would be as follows:

    SELECT * FROM countries ORDER BY code='USA' DESC, code='CAN' DESC, name ASC
    

    Of course in answering the OP's question, I like the FIELD() option best - quite clean :-)

提交回复
热议问题