การ ORDER BY ด้วยนิพจน์คณิตศาสตร์ (Expression)
MySQL รองรับการใช้ Expression (นิพจน์คำนวณ) ใน ORDER BY โดยตรง เช่น Quantity * Price คำนวณค่าในแต่ละแถว แล้วเรียงตามผลลัพธ์
ตัวอย่างการใช้งาน
สร้างตารางสินค้า:
mysql> CREATE TABLE orderByMathCalculation (
-> Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> Quantity INT, Price INT
-> );
Query OK, 0 rows affected (0.57 sec)
mysql> INSERT INTO orderByMathCalculation(Quantity, Price) VALUES(10,50),(20,40),(2,20),(11,10);
Query OK, 4 rows affected (0.15 sec)
ข้อมูลทั้งหมด:
mysql> SELECT * FROM orderByMathCalculation;
+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 1 | 10 | 50 |
| 2 | 20 | 40 |
| 3 | 2 | 20 |
| 4 | 11 | 10 |
+----+----------+-------+
4 rows in set (0.00 sec)
กรณี 1: เรียง ASC ตามมูลค่า (Quantity × Price)
mysql> SELECT * FROM orderByMathCalculation ORDER BY Quantity * Price;
+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 3 | 2 | 20 | -- 40
| 4 | 11 | 10 | -- 110
| 1 | 10 | 50 | -- 500
| 2 | 20 | 40 | -- 800
+----+----------+-------+
4 rows in set (0.00 sec)
กรณี 2: เรียง DESC ตามมูลค่า
mysql> SELECT * FROM orderByMathCalculation ORDER BY Quantity * Price DESC;
+----+----------+-------+
| Id | Quantity | Price |
+----+----------+-------+
| 2 | 20 | 40 | -- 800
| 1 | 10 | 50 | -- 500
| 4 | 11 | 10 | -- 110
| 3 | 2 | 20 | -- 40
+----+----------+-------+
4 rows in set (0.00 sec)
คำอธิบายและประยุกต์ใช้
- Expression ใน ORDER BY คำนวณต่อแถว (Row-by-row) รองรับ + - * / ฟังก์ชันต่างๆ
- ตัวอย่าง:
ORDER BY (price * qty) - discount,ORDER BY DATEDIFF(end_date, start_date) - สามารถใช้ Alias ที่ประกาศใน SELECT ได้:
SELECT ..., Quantity*Price AS Total FROM ... ORDER BY Total
ข้อควรระวังประสิทธิภาพ
Expression ใน ORDER BY ทำให้ Index ไม่ถูกใช้งาน (Filesort) หาก Query บ่อยและตารางใหญ่ ควร:
- เพิ่ม Generated Column:
ADD COLUMN total_value INT GENERATED ALWAYS AS (Quantity * Price) STORED - สร้าง Index:
CREATE INDEX idx_total ON orderByMathCalculation(total_value) - แล้ว ORDER BY total_value
วิธีนี้ทำให้ Index ใช้ได้ (Index Sort) เร็วกว่ามาก