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

ใช้ Backticks จัดการ Table Name ที่เป็น Reserved Word (order) ใน MySQL


ปัญหา

ORDER เป็น Reserved Word ใน MySQL (ใช้ใน ORDER BY) ไม่สามารถใช้เป็น Table/Column Name ได้โดยตรง

วิธีแก้: ใช้ Backticks (`)

ห่อชื่อ Identifier (Table, Column, Database) ด้วย Backticks เพื่อบอก MySQL ว่าเป็น Identifier ไม่ใช่ Keyword

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

1. สร้างตารางชื่อ order

mysql> CREATE TABLE `order` (
    -> StudentId INT
    -> );
Query OK, 0 rows affected (1.78 sec)

2. เพิ่มข้อมูล

mysql> INSERT INTO `order` VALUES(101);
Query OK, 1 row affected (0.26 sec)
mysql> INSERT INTO `order` VALUES(210);
Query OK, 1 row affected (0.18 sec)
mysql> INSERT INTO `order` VALUES(190);
Query OK, 1 row affected (0.28 sec)
mysql> INSERT INTO `order` VALUES(180);
Query OK, 1 row affected (0.46 sec)
mysql> INSERT INTO `order` VALUES(205);
Query OK, 1 row affected (0.28 sec)

3. Query ข้อมูล (ต้องใช้ Backticks ทุกครั้ง)

mysql> SELECT * FROM `order`;

ผลลัพธ์:

+-----------+
| StudentId |
+-----------+
| 101       |
| 210       |
| 190       |
| 180       |
| 205       |
+-----------+
5 rows in set (0.00 sec)

4. Query พร้อม ORDER BY (Reserved Word ชนกัน)

mysql> SELECT * FROM `order` ORDER BY StudentId DESC LIMIT 1;

ผลลัพธ์:

+-----------+
| StudentId |
+-----------+
| 210       |
+-----------+
1 row in set (0.03 sec)

Reserved Words ที่พบบ่อย

Reserved Word ใช้ใน ตัวอย่าง Escape
ORDER ORDER BY `order`
GROUP GROUP BY `group`
SELECT SELECT `select`
INDEX INDEX `index`
KEY PRIMARY KEY `key`
TABLE TABLE `table`
DATABASE DATABASE `database`
USER USER() `user`
RANK Window Function (MySQL 8.0+) `rank`
DESC DESC / DESCRIBE `desc`

Best Practice

  • หลีกเลี่ยง Reserved Words ตั้งชื่อ Table/Column ให้สื่อความหมายและไม่ชน Keyword
  • ใช้ Prefix: tbl_order, order_table, orders
  • หากต้องใช้ Reserved Word → ใช้ Backticks ทุกครั้ง ที่อ้างอิง
  • Application Code (ORM, Query Builder) มัก Escape ให้อัตโนมัติ

ตั้งค่า SQL Mode: ANSI_QUOTES

SET SQL_MODE = 'ANSI_QUOTES';
-- แล้วจะใช้ Double Quote สำหรับ Identifier แทน Backticks
CREATE TABLE "order" (Id INT);
SELECT * FROM "order";

ข้อควรระวัง: Double Quote จะไม่สามารถใช้สำหรับ String Literal ได้อีก (ต้องใช้ Single Quote เท่านั้น)