基于WHERE IN子句数据的结果集 [英] Order resultset based on WHERE IN clause data
问题描述
考虑这个MySQL查询:
Considering this MySQL query:
SELECT
someColumns
FROM
someTable
WHERE
someColumn IN ( value1, value2, value3 )
我保证行集合按照给定给 IN()
子句的值的顺序排序?我假设这不是保证没有给它一个 ORDER BY
子句,是吗?
... 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。 :
IN()
子句中的值将是由PHP传递给查询的任意数据的数组(使用Zend Framework选择语句):
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 );
推荐答案
在ORDER BY中使用CASE语句:
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
根据需要分配任意值。我通常不会在 ORDER BY
中包含 ASC
,因为它是隐含的,如果没有定义,但我想明确如果您希望在 DESC
订单。
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.
这篇关于基于WHERE IN子句数据的结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!