开发者

Why does the update command in sql insist on using slanted single quotes?

I have been having trouble updating some fields in a mysql database, and I am frustrated that at times mysql refuses to allow me to query unless I wrap fields in slanted quotes rather than single ones. It seems to have no discernible pattern for doing so, could someone explain what is going on here?

This query works with no quote开发者_如何学Cs of any kind (x is primary key)

UPDATE  table SET  x =  1821 WHERE  x =1820

These two querys fail with syntax problems near the o.

UPDATE  table SET  o =  200 WHERE  x =1820

UPDATE  table SET  'o' =  200 WHERE  x =1820

This query works.

UPDATE  table SET  `o` =  200 WHERE  x =1820

Is there any legitimate reason mysql is insistent on using the slanted quotes?


In almost all SQL dialects, strings (like input values) go single quoted and identifiers (like table or column names) go unquoted:

SELECT column_name, function_name() AS column_alias
FROM table_name
WHERE another_column='The value to match'

This is valid for MySQL, Oracle, SQL-Server and a long etcetera.

This is the general rule. Then, there's a particular situation: when you want to use certain name for an identifier that would normally be invalid. In such case, MySQL allows you to use backtick quotes around the name (other DBMS use square brackets, double quotes or simply don't allow you to use such name):

SELECT `Full Name` -- Name with spaces
FROM `from` -- Reserved word

In general, it's better to simply avoid these kind of names, although I understand there are cases where a really good name is already taken:

SELECT `key`, value
FROM settings

As about your examples, it's obvious that they aren't real queries since using table as a table name would trigger a syntax error in them all ;-)


It means that o is a reserved word for MySQL, that's why you can't just put o. You cannot use 'o' for specifying a column name, single quotes is for values. Slanted quotes are to specify Column names, this removes the problem of having reserved words. If you want to be sure you should always use `` for tables and column names.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜