我们如何"order by"过滤顺序



为了将SQL查询按我们在in子句中注入的ID排序,我们可以做什么技巧?

喜欢:

select oh.orderID, oh.orderType, oh.state, oh.orderDateTime
from orderHeaders oh 
where oh.orderID in (
47185154,
47185121,
47184971,
47863101)

我的orderID字段如下:

47184971...
47863101...
47185121...
47185154...

如何获得按WHERE IN (...)过滤器中排序的条目排序的结果?

您可以使用

field()

select oh.orderID, oh.orderType, oh.state, oh.orderDateTime
from orderHeaders oh 
where oh.orderID in (47185154, 47185121, 47184971, 47863101)
order by field(oh.orderID, 47185154, 47185121, 47184971, 47863101);

您可以在 order by 子句中定义它们

ORDER BY
CASE oh.OrderID 
WHEN '47185154' THEN 1
WHEN '47185121' THEN 2
WHEN '47184971' THEN 3
WHEN '47863101' THEN 4
ELSE 5
END

最新更新