การอ้างอิงคอลัมน์ที่ชื่อซ้ำกับ Reserved Keyword ใน MySQL
ใช้ **Backtick (`)** ครอบชื่อคอลัมน์/ตารางที่เป็น Keyword เพื่อไม่ให้ MySQL ผิดเพี้ยน
ตัวอย่างการใช้งาน
สร้างตารางมีคอลัมน์ชื่อ select (เป็น Keyword):
mysql> create table DemoTable (`select` varchar(100));
เพิ่มข้อมูล:
mysql> insert into DemoTable values('Records');
mysql> insert into DemoTable values('All Data');
mysql> insert into DemoTable values('Information');
SELECT โดยใช้ Backtick:
mysql> select `select` from DemoTable;
+-------------+ | select | +-------------+ | Records | | All Data | | Information | +-------------+
Keyword ที่พบบ่อยและต้อง Escape:
select, insert, update, delete, from, where, order, group, by, limittable, index, key, primary, unique, foreign, referencesuser, password, database, schema, function, proceduredesc, asc, like, between, in, exists, null, true, false
แนวทางปฏิบัติที่ดี (Best Practice):
- หลีกเลี่ยงการใช้ Keyword เป็น Identifier เลย
- ถ้าบังคับต้องใช้ ให้ Escape ด้วย Backtick
`ทุกครั้ง - ตั้งค่า
sql_mode=ANSI_QUOTESจะใช้ Double Quote"แทน Backtick ได้ (แต่ไม่ใช่ค่า Default)