“ where in ” mysql clause

前端 未结 5 747
梦毁少年i
梦毁少年i 2021-01-02 19:36

i used a mysql query where there is \"where id in (\"22,20,21\") \" but when i get the result its like array ordered in asecending order ie 20,21,20

but i need it i

相关标签:
5条回答
  • 2021-01-02 20:13

    SQL results are unordered unless given an explicit ordering; the order won't be picked up from the in clause.

    Since the IDs are neither ASC nor DESC either, you'd have to ORDER BY something else; how are you determining the 22,20,21 order in the first place?

    0 讨论(0)
  • 2021-01-02 20:14

    As mentioned... WHERE clause doesn't do anything with ordering of result set. Use MySQL built-in FIELD function in ORDER BY clause to specify how the result set should be ordered:

    ... WHERE id IN (22, 20, 21) ORDER BY FIELD(id, 22, 20, 21) ...
    
    0 讨论(0)
  • 2021-01-02 20:31

    i think you should be able to use the FIELD keyword like so:

    SELECT * FROM table
    WHERE id in (22,20,21)
    ORDER BY FIELD(id,22,20,21);
    

    this is mysql specific, and seems magical, but it works.

    0 讨论(0)
  • 2021-01-02 20:37

    You cannot specify the order results will be returned in in a WHERE clause. If you want to specify order, you need to add an ORDER BY clause to your query. For a solution that uses FIND_IN_SET see this answer.

    0 讨论(0)
  • 2021-01-02 20:39

    In general, the database system returns the results in whatever order it feels like. If you want it to be ordered, you have to tell it. This blog post provides one method for doing so; you may be able to find other solutions online.

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