This question has already been answered:

I make a request to the database for the selection of goods by id , and id follow in a certain order. For example, part of the query FROM oc_product p WHERE p.product_id IN ('574','572','573') . In response, I get a sorted array. I need to get an array with the same id order as in the request. Processing the php array has already implemented. I wonder whether it is possible to preserve the order of the id sql query

Reported as a duplicate by members Mike , Denis , pavel , aleksandr barakin , tutankhamun 19 Sep '16 at 20:09 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    You can use the FIELD() function, passing it the exact same sequence that you specify in IN . The function will return the index of the value in the sequence and can be sorted by the ORDER BY .

     SELECT * FROM oc_product p WHERE p.product_id IN ('574','572','573') ORDER BY FIELD(p.product_id, '574','572','573') 
    • one
      Try not to produce the same answers to the same questions. In the base of StackOverflow many absolutely identical questions come to nothing. Doubles should be closed. - Mike