MySQL sort after argument in IN()

前端 未结 4 1326
刺人心
刺人心 2020-12-07 03:55

I have string containing a lot of IDs corresponding to my database. Like:

1,2,3,4,5

I then do a mySQL query to select all those rows:

4条回答
  •  长情又很酷
    2020-12-07 04:21

    You should be able to do this via the FIELD() function like so:

    SELECT * FROM `table` WHERE `id` IN (2,1,3,4,5) ORDER BY FIELD(`id`, 2,1,3,4,5) DESC
    

    That is:

    SELECT
      *
    FROM
      `table`
    WHERE
      `id` IN (".$myIDs.")
    ORDER BY
      FIELD(`id`, ".$myIDs.") DESC
    

    More in this blog post: Sorting MySQL rows using column values.

提交回复
热议问题