开发者

MySQL INSERT with table alias

I happen to have two columns having the same name as two SQL reserved words, Key and Value. When using the SELECT statement I can create a table alias and solve it that way.

Now I'm trying to INSERT data and it seems like you can't create table alias in the INSERT statement.

INSERT INTO attributeStrings ats
(ats.ItemID,ats.Key,ats.Value)
VALUES (3,'Categories','TechGUI')

I get error at 'ats (ats.ItemID,ats.Key,ats.Value) VALUES (3,'Categorie开发者_开发百科s','TechGUI')' indicating that alias can't be created.

Are there any ways to solve this without renaming the columns Key and Value?


Use back-tick to escape reserved words.

  INSERT INTO `attributeStrings` (`ItemID`, `Key`,`Value`) VALUES (3,'Categories','TechGUI')

Looks like insert does not support alias. see here


Edit: ok, the MySQL ref says no alias in insert


It does work

mysql> INSERT INTO `attributeStrings` (`ItemID`, `Key`,`Value`) VALUES (3,'Categories','TechGUI');
Query OK, 1 row affected (0.03 sec)

mysql> select * from attributeStrings;
+--------+------------+---------+
| ItemId | Key        | Value   |
+--------+------------+---------+
|      3 | Categories | TechGUI |
+--------+------------+---------+
1 row in set (0.00 sec)


Is easy to be the wise guy based on your question

INSERT INTO attributeStrings
VALUES (3,'Categories','TechGUI');
/* if the table have more than 3 columns, fill-up every column then */

Other problems

Meaningless to have camelCase, because windows does not support file name with case sensitive yet.

So, you practically can have same table with different case in linux/mac, but not on windows

mysql> create table abc (id int(10));
Query OK, 0 rows affected (0.00 sec)

mysql> create table abC (id int(10));
Query OK, 0 rows affected (0.01 sec)


Key is a

RESERVED WORD

In Mysql so it needs to be quoted

You can check all Reserved words here


it seems like you can't create table alias in the INSERT statement

Some SQL products (e.g. SQL Server) do allow this but I'm not sure that's a good thing.

According to SQL Standards, an alias should have the effect of the table being materialized i.e. an INSERT (or any other flavour of update) to an aliased table should leave the underlying base table(s) unaffected.

In SQL Server, such an INSERT does affect the underlying base table(s) but I think the actual (non-compliant) effect is what most SQL coders would expect to happen in that situation. Put another way, a valid INSERT statement that resulted in no rows being added I think would initially be suspected as a bug, even though that's the way Standard SQL is supposed to work.

So I think disallowing the situation to arise in the first place, while again being technically non-compliant with Standards, is desireable, in my opinion.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜