gpt4 book ai didi

mysql - 为什么 MySQL 不按照 IN 子句中出现的顺序返回行?

转载 作者:行者123 更新时间:2023-11-29 12:22:53 24 4
gpt4 key购买 nike

此查询要求 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 不按“正确”的顺序返回项目。

最佳答案

如果您想保留 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)
;

关于mysql - 为什么 MySQL 不按照 IN 子句中出现的顺序返回行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28768108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com