我可以按IN查询的值排序吗?
以下默认为"订购item_id最低优先"但我实际上希望排序为输入...这可能吗?
例如
select item_id, item_title, item_source from items where item_id IN ('1676','1559','1672')
Run Code Online (Sandbox Code Playgroud)
我想回来:
item_id item_title item_source
------- ---------- -----------
1676 item_a source_a
1559 item_f source_f
1672 item_c source_c
Run Code Online (Sandbox Code Playgroud)
你可以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
Run Code Online (Sandbox Code Playgroud)
您需要一个自定义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
Run Code Online (Sandbox Code Playgroud)
如果您事先已经知道 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')
Run Code Online (Sandbox Code Playgroud)
或者
ORDER BY FIND_IN_SET(item_id, '1676,1559,1672')
Run Code Online (Sandbox Code Playgroud)
当然,缺点是您需要指定两次 ID。不过,我认为几乎任何性能合理的解决方案都会这样做。解决这个问题的唯一方法是有一个排序顺序字段或类似的东西。