我可以按IN值订购吗?

时间:2012-11-04 20:25:05

标签: mysql sql

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

以下默认为“order item_id first first first”但我实际上希望排序为输入...这可能吗?

e.g。

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

3 个答案:

答案 0 :(得分:7)

您可以在JOIN谓词中IN 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 这样的值:

{{1}}

SQL Fiddle Demo

答案 1 :(得分: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

答案 2 :(得分:4)

如果您事先已经知道了ID,则可以考虑使用FIND_IN_SETFIELD函数来整理结果。

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。不过,我正在考虑任何合理执行的解决方案。解决这个问题的唯一方法就是有一个排序顺序字段或类似的东西。