คำสั่ง IN() จะเรียงผลลัพธ์ตามคอลัมน์อัตโนมัติ ใช้ ORDER BY FIND_IN_SET() เพื่อคงลำดับตามที่ระบุใน IN clause
ตัวอย่างการใช้งาน
สร้างตาราง:
mysql> create table ProductStock (
-> ProductId int, ProductName varchar(20), ProductQuantity int, ProductPrice float
-> );
เพิ่มข้อมูล:
mysql> INSERT INTO ProductStock VALUES (1,'Product-101',10,500.56),(25,'Product-111',5,150.00), (67,'Product-311',7,1000.50),(55,'Product-561',8,900.00), (75,'Product-221',15,670.56);
ข้อมูล:
+-----------+-------------+-----------------+--------------+ | 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 | +-----------+-------------+-----------------+--------------+
SELECT ด้วย IN(25,55,67,75,1) และ ORDER BY 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');
ผลลัพธ์ (เรียงตามลำดับใน IN clause):
+-----------+-------------+-----------------+--------------+ | 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 | +-----------+-------------+-----------------+--------------+
หากไม่ใช้ ORDER BY FIND_IN_SET จะได้ลำดับ 1,25,55,67,75 (เรียงตามค่า ProductId)