8

我可以按 IN 查询的值排序吗?

以下默认为“order item_id 最低优先”,但我实际上想要输入的排序......这可能吗?

例如

select item_id, item_title, item_source from items where item_id IN ('1676','1559','1672')

我想返回:

item_id     item_title    item_source
-------     ----------    -----------
1676        item_a        source_a
1559        item_f        source_f
1672        item_c        source_c
4

3 回答 3

7

您可以像这样JOININ谓词中使用这些值:

SELECT 
  i.item_id,
  i.item_title
  i.item_source
FROM items i
INNER JOIN
(
   SELECT 0 sortid, 1676 id
   UNION ALL
   SELECT 1,        1559 
   UNION ALL
   SELECT 2,        1672
) t ON i.item_id = t.id
ORDER BY t.sortid

SQL 小提琴演示

于 2012-11-04T20:33:42.323 回答
6

您需要一个自定义ORDER BY CASE来对每个可能的值应用排序等级。显然,随着集合大小的增加,这变得困难。

select
  item_id, 
  item_title, 
  item_source 
from items
where item_id IN ('1676','1559','1672')
/* Custom ORDER BY applies lower order numbers to the lowest value, etc... */
ORDER BY 
  CASE 
    WHEN item_id = 1676 THEN 0
    WHEN item_id = 1559 THEN 1
    WHEN item_id = 1672 THEN 2
    /* If you had others (which you don't because they're limited by the IN() clause, include an ELSE */
    ELSE 99
  END,
  /* Then complete the ORDER BY with other cols to order on as needed... */
  item_source
于 2012-11-04T20:27:04.507 回答
4

如果您事先已经知道 ID,则可以考虑使用FIND_IN_SET或函数来组织结果。FIELD

SELECT 
    item_id,
    item_title,
    item_source
FROM items
WHERE item_id IN ('1676','1559','1672')
ORDER BY FIELD(item_id, '1676', '1559', '1672')

或者

ORDER BY FIND_IN_SET(item_id, '1676,1559,1672')

当然,缺点是您指定了两次 ID。不过,我认为几乎任何合理执行的解决方案都会这样做。解决这个问题的唯一方法是有一个排序字段或类似的东西。

于 2012-11-04T20:59:35.737 回答