开发者

Why put ` around columns?

In some code i see people put ` around their columns. Why? IS there any difference from not using them?

SELECT `players`.`name`, `houses`.`id` FROM `players`, `houses` 
WH开发者_开发问答ERE `houses`.`owner` = `players`.`id`


Using the backquotes allows reserved words to be used as column or table names e.g.

SELECT `values` FROM `references` WHERE `precision` > 0

and names with nonalphanumerics must be enclosed between the "`"s too, e.g.

SELECT `user name` FROM `registered users` WHERE `total score` > 0

See http://dev.mysql.com/doc/refman/5.1/en/identifiers.html for detail.


I think this is often seen when those names are used dynamically, e.g. (artificial example)

mysql_prepare_statement("SELECT `%q` FROM `%q` WHERE `%q` > 0", col, tbl, col_cond);

in this form, any kinds of column and table names can be handled identically, and malicious injection attempts such as col = "1; DROP TABLE users--" can be avoided.


Some column names might be reserved words in MySQL. In such cases you can quote them with `. For the sake of consistency and future-proofing, some developers quote all identifiers.


A common term for backticks used in this fashion is "identifier quotes". They are used to enclose the names of schema objects (tables, columns, procedures, triggers, etc etc). They are used because they allow otherwise illegal characters (spaces, punctuation characters, etc.) and SQL reserved words to appear within (or as the entirety of) the object name.

Using backticks for this purpose is MySQL-specific. In the ANSI standard for SQL, identifiers are supposed to be enclosed in double-quotes ". MySQL regards " as a string delimiter by default, but if you set the SQL mode to include ANSI_QUOTES, it will regard " as an alternative identifier quote mark instead (backticks will still work too). Other RDBMSs also have proprietary identifier characters as well; for example SQL Server permits you to use [...] as well as "...".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜