使用 MySQL IN() 進行選擇查詢並避免對它進行排序
使用 IN() 對特定欄位進行結果排序。為了避免這種情況,請對該欄位使用 ORDER BY 和 FIND_IN_SET()。
為了理解 find_in_set(),讓我們建立一個表。建立表的查詢如下 −
mysql> create table ProductStock -> ( -> ProductId int, -> ProductName varchar(20), -> ProductQuantity int, -> ProductPrice float -> ); Query OK, 0 rows affected (0.79 sec)
現在,您可以使用插入命令在表中插入一些記錄。查詢如下 −
mysql> insert into ProductStock values(1,'Product-101',10,500.56); Query OK, 1 row affected (0.20 sec) mysql> insert into ProductStock values(25,'Product-111',5,150.00); Query OK, 1 row affected (0.21 sec) mysql> insert into ProductStock values(67,'Product-311',7,1000.50); Query OK, 1 row affected (0.60 sec) mysql> insert into ProductStock values(55,'Product-561',8,900.00); Query OK, 1 row affected (0.24 sec) mysql> insert into ProductStock values(75,'Product-221',15,670.56); Query OK, 1 row affected (0.14 sec)
使用 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)
廣告