此查询要求MySQL从product
表返回项目。我希望按照IN
子句中的顺序返回结果。
select id, price
from product
where id IN (5552902, 5552737, 5552887, 5549436, 5552291, 5552897,
5550834, 5552794, 5548666, 5552621);
+---------+----------+
| id | price |
+---------+----------+
| 5548666 | 919.0000 |
| 5549436 | 939.0000 |
| 5550834 | 919.0000 |
| 5552291 | 939.0000 |
| 5552621 | 829.0000 |
| 5552737 | 999.0000 |
| 5552794 | 919.0000 |
| 5552887 | 999.0000 |
| 5552897 | 939.0000 |
| 5552902 | 999.0000 |
+---------+----------+
由于某种原因,MySQL在不遵守订单的情况下返回结果,我必须使用ORDER BY price DESC
才能获得所需的结果。
select id, price
from product
where id IN (5552902, 5552737, 5552887, 5549436, 5552291,
5552897, 5550834, 5552794, 5548666, 5552621)
ORDER BY price DESC;
+---------+----------+
| id | price |
+---------+----------+
| 5552902 | 999.0000 |
| 5552887 | 999.0000 |
| 5552737 | 999.0000 |
| 5552291 | 939.0000 |
| 5549436 | 939.0000 |
| 5552897 | 939.0000 |
| 5550834 | 919.0000 |
| 5552794 | 919.0000 |
| 5548666 | 919.0000 |
| 5552621 | 829.0000 |
+---------+----------+
MySQL版本为5.6
。我想知道为什么MySQL不会以“正确”的顺序返回项目。
答案 0 :(得分:1)
如果您想保留in clause
中的订单,可以使用order by field
某些内容
select
id, price from product
where id IN (5552902, 5552737, 5552887, 5549436, 5552291, 5552897, 5550834, 5552794, 5548666, 5552621)
order by field(id,5552902, 5552737, 5552887, 5549436, 5552291, 5552897, 5550834, 5552794, 5548666, 5552621)
;