Escaping Reserved Words as Column Names in MySQL CREATE TABLE
When creating tables in MySQL, it is important to adhere to the language's reserved keywords. However, challenges arise when class field names match these keywords, such as the "key" field in the example provided.
To bypass this issue, you can utilize double quotes or backticks to escape the reserved word, ensuring its recognition as a column name rather than a MySQL keyword.
Using Double Quotes (ANSI SQL Mode Enabled)
If the ANSI SQL mode is enabled in your MySQL environment, you can enclose the reserved word within double quotes:
CREATE TABLE IF NOT EXISTS misc_info ( id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, "key" TEXT UNIQUE NOT NULL, value TEXT NOT NULL ) ENGINE=INNODB;
Using Backticks (Proprietary Escaping)
If the ANSI SQL mode is not enabled or you prefer a proprietary approach, you can use backticks to escape the reserved word:
CREATE TABLE IF NOT EXISTS misc_info ( id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, `key` TEXT UNIQUE NOT NULL, value TEXT NOT NULL ) ENGINE=INNODB;
By employing either of these methods, you can successfully create tables with column names that coincide with MySQL reserved words.
The above is the detailed content of How Can I Escape Reserved Words When Creating MySQL Table Columns?. For more information, please follow other related articles on the PHP Chinese website!