ใน MySQL สามารถใช้คำนวณทางคณิตศาสตร์โดยตรงในคำสั่ง ORDER BY ได้ เช่น การเรียงตามผลต่างของคอลัมน์ตัวเลขสองคอลัมน์
รูปแบบคำสั่ง
SELECT * FROM yourTableName ORDER BY (yourIntegerColumn1 - yourIntegerColumn2);
ตัวอย่างการใช้งาน
สร้างตารางเก็บคะแนนสองรอบ:
mysql> create table DemoTable1313 (Name varchar(20), Score1 int, Score2 int);
mysql> insert into DemoTable1313 values('Chris',40,60);
mysql> insert into DemoTable1313 values('David',70,50);
mysql> insert into DemoTable1313 values('Adam',35,30);
ข้อมูลต้นฉบับ:
+-------+--------+--------+ | Name | Score1 | Score2 | +-------+--------+--------+ | Chris | 40 | 60 | | David | 70 | 50 | | Adam | 35 | 30 | +-------+--------+--------+
คำสั่งเรียงตามความต่าง (Score1 - Score2)
mysql> select * from DemoTable1313 order by (Score1-Score2);
ผลลัพธ์ (เรียงจากต่างน้อยไปมาก / ลบไปบวก)
+-------+--------+--------+ | Name | Score1 | Score2 | +-------+--------+--------+ | Chris | 40 | 60 | --> -20 | Adam | 35 | 30 | --> +5 | David | 70 | 50 | --> +20 +-------+--------+--------+
ประยุกต์ใช้: เปลี่ยนเป็น ORDER BY (Score1-Score2) DESC เพื่อเรียงจากต่างมากไปน้อย หรือใช้ ABS(Score1-Score2) เพื่อเรียงตามค่าสัมบูรณ์ของความต่าง