使用 MySQL IN() 选择查询并避免在其中排序
使用IN()对特定字段的结果进行排序。为避免这种情况,请FIND_IN_SET()对字段使用ORDERBY和。
为了理解find_in_set(),让我们创建一个表。创建表的查询如下-
mysql> create table ProductStock -> ( -> ProductId int, -> ProductName varchar(20), -> ProductQuantity int, -> ProductPrice float -> );
现在您可以使用插入命令在表中插入一些记录。查询如下-
mysql> insert into ProductStock values(1,'Product-101',10,500.56); mysql> insert into ProductStock values(25,'Product-111',5,150.00); mysql> insert into ProductStock values(67,'Product-311',7,1000.50); mysql> insert into ProductStock values(55,'Product-561',8,900.00); mysql> insert into ProductStock values(75,'Product-221',15,670.56);
使用select语句显示表中的所有记录。查询如下-
mysql> select *from ProductStock;输出结果
+-----------+-------------+-----------------+--------------+ | ProductId | ProductName | ProductQuantity | ProductPrice | +-----------+-------------+-----------------+--------------+ | 1 | Product-101 | 10 | 500.56 | | 25 | Product-111 | 5 | 150 | | 67 | Product-311 | 7 | 1000.5 | | 55 | Product-561 | 8 | 900 | | 75 | Product-221 | 15 | 670.56 | +-----------+-------------+-----------------+--------------+ 5 rows in set (0.00 sec)
这是find_in_set()用于查询的查询-
mysql> select *from ProductStock -> where ProductId IN(25,55,67,75,1) -> order by find_in_set(ProductId,'25,55,67,75,1');输出结果
+-----------+-------------+-----------------+--------------+ | ProductId | ProductName | ProductQuantity | ProductPrice | +-----------+-------------+-----------------+--------------+ | 25 | Product-111 | 5 | 150 | | 55 | Product-561 | 8 | 900 | | 67 | Product-311 | 7 | 1000.5 | | 75 | Product-221 | 15 | 670.56 | | 1 | Product-101 | 10 | 500.56 | +-----------+-------------+-----------------+--------------+ 5 rows in set (0.31 sec)
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下