Ordering by the order of values in a SQL IN() clause

前端 未结 13 791
旧巷少年郎
旧巷少年郎 2020-11-22 04:12

I am wondering if there is away (possibly a better way) to order by the order of the values in an IN() clause.

The problem is that I have 2 queries, one that gets al

13条回答
  •  你的背包
    2020-11-22 04:44

    Use MySQL's FIELD() function:

    SELECT name, description, ...
    FROM ...
    WHERE id IN([ids, any order])
    ORDER BY FIELD(id, [ids in order])
    

    FIELD() will return the index of the first parameter that is equal to the first parameter (other than the first parameter itself).

    FIELD('a', 'a', 'b', 'c')

    will return 1

    FIELD('a', 'c', 'b', 'a')

    will return 3

    This will do exactly what you want if you paste the ids into the IN() clause and the FIELD() function in the same order.

提交回复
热议问题