Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ใช้ ORDER BY กับตัวแปร User-Defined Variable แบบ Numeric ใน MySQL

สามารถใช้ตัวแปร User-Defined Variable (@variable) ร่วมกับ PREPARE และ EXECUTE เพื่อสร้าง Dynamic ORDER BY ที่ระบุคอลัมน์ได้จากตัวแปร

ตัวอย่างการใช้งาน

1. สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable1898 ( Number int ); Query OK, 0 rows affected (0.00 sec)

mysql> insert into DemoTable1898 values(10); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(70); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(30); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(50); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(40); Query OK, 1 row affected (0.00 sec)

ข้อมูลต้นฉบับ (ไม่เรียง):

mysql> select * from DemoTable1898;
+--------+
| Number |
+--------+
|     10 |
|     70 |
|     30 |
|     50 |
|     40 |
+--------+
5 rows in set (0.00 sec)

2. ใช้ตัวแปร @limitValue กำหนดคอลัมน์ ORDER BY

mysql> set @limitValue := 1;  -- คอลัมน์ที่ 1 (Number)
Query OK, 0 rows affected (0.00 sec)

mysql> set @query := CONCAT('select * from DemoTable1898 order by ', @limitValue);
Query OK, 0 rows affected (0.00 sec)

mysql> prepare stmt from @query; Query OK, 0 rows affected (0.00 sec) Statement prepared

mysql> execute stmt;

ผลลัพธ์ (เรียงตามคอลัมน์ที่ 1 = Number):

+--------+
| Number |
+--------+
|     10 |
|     30 |
|     40 |
|     50 |
|     70 |
+--------+
5 rows in set (0.00 sec)

3. ล้าง Prepared Statement

mysql> deallocate prepare stmt; Query OK, 0 rows affected (0.00 sec)

ขั้นตอนสร้าง Dynamic SQL

  1. SET @var = value - กำหนดค่าตัวแปร
  2. SET @query = CONCAT('SQL template ', @var) - สร้าง Query String
  3. PREPARE stmt FROM @query - คอมไพล์ Prepared Statement
  4. EXECUTE stmt - รัน Statement
  5. DEALLOCATE PREPARE stmt - ปล่อยทรัพยากร

กรณีใช้ ORDER BY คอลัมน์ที่ 2, 3, ...

SET @col := 2;
SET @sql := CONCAT('SELECT * FROM DemoTable1898 ORDER BY ', @col);
PREPARE stmt FROM @sql;
EXECUTE stmt;

⚠️ ข้อควรระวัง

  • SQL Injection Risk: ต้อง Validate @variable ให้เป็นตัวเลข/ชื่อคอลัมน์ที่อนุญาตเท่านั้น
  • ไม่สามารถใช้ Variable โดยตรงใน ORDER BY ได้: ORDER BY @var จะ Error
  • Prepared Statement ใช้ Session Scope หายเมื่อ Disconnect

สรุป: ใช้ PREPARE/EXECUTE ร่วมกับ CONCAT() และ User Variable เพื่อ Dynamic ORDER BY ใน MySQL ต้อง Validate Input เพื่อป้องกัน Injection