Order resultset based on WHERE IN clause data

假装没事ソ 提交于 2019-12-07 10:08:31

问题


Considering this MySQL query:

SELECT
  someColumns
FROM
  someTable
WHERE
  someColumn IN ( value1, value2, value3 )

... how can I guarantee that the rowset comes out ordered in the exact order of the values given to the IN () clause? I presume this is not guaranteed without giving it an ORDER BY clause, is it?

PS.:
The values to the IN () clause will be an array of arbitrary data passed to the query by PHP (utilizing Zend Framework's select statement) in the following manner:

->where( 'someColumn in (?)', $theArrayWithValues );

回答1:


Use a CASE statement in the ORDER BY:

ORDER BY CASE someColumn
           WHEN value1 THEN 1
           WHEN value2 THEN 2
           WHEN value3 THEN 3
         END ASC

Assign the arbitrary values as you like. I don't normally include ASC in ORDER BY because it is implied if not defined, but I wanted to be explicit in case you want in DESC order.




回答2:


No, the order is not guaranteed - or rather, it will be the order the selected rows appear in the database.

If you know the values will belong to a strict set you can make the column an ENUM type with the order you want, and sorting on this field will sort by that order.

One simple way to order by certain values is this:

ORDER BY `someColumn`='value1' DESC, `someColumn`='value2' DESC, ...


来源:https://stackoverflow.com/questions/2245936/order-resultset-based-on-where-in-clause-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!