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

เลือกคอลัมน์ที่ชื่อซ้ำกับ Keyword ใน MySQL

การอ้างอิงคอลัมน์ที่ชื่อซ้ำกับ 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, limit
  • table, index, key, primary, unique, foreign, references
  • user, password, database, schema, function, procedure
  • desc, asc, like, between, in, exists, null, true, false

แนวทางปฏิบัติที่ดี (Best Practice):

  1. หลีกเลี่ยงการใช้ Keyword เป็น Identifier เลย
  2. ถ้าบังคับต้องใช้ ให้ Escape ด้วย Backtick ` ทุกครั้ง
  3. ตั้งค่า sql_mode=ANSI_QUOTES จะใช้ Double Quote " แทน Backtick ได้ (แต่ไม่ใช่ค่า Default)