开发者

Insert into on duplicate update Mysql error

I'm trying to insert on duplicate key update in Mysql using below:

INSERT INTO `generic_client_data` (id, keyword, client_id, desc_id) 
VALUES (NULL, qqqq, 115, 0) ON DUPLICATE KEY 
UPDATE keyword=VALUES(qqqq), client_id=VALUES(115), desc_id=VALUES(0)

but it gives me this error:

#1064 - You have an error in your SQL syntax; check the manual that 
        corresponds to your MySQL server version for the right syntax 
        to use near '115), desc_id=VALUES(0)' at line 1

Is there a reason开发者_如何学运维 why?


The VALUES "function" in the UPDATE part of the query refers to the column names that you used in the INSERT part. What you want is this:

INSERT INTO `generic_client_data` (id, keyword, client_id, desc_id) 
VALUES (NULL, 'qqqq', 115, 0) ON DUPLICATE KEY 
UPDATE keyword=VALUES(keyword), client_id=VALUES(client_id), desc_id=VALUES(desc_id);

This way, you can refer back to whatever values you wanted to insert; they may be calculated values, or they may have come from a SELECT query. When you get into more complex queries, I think you'll find this much more convenient than what you were trying to do.

Most of the time, when you use ON DUPLICATE KEY UPDATE, you will have no reason to do anything other than

UPDATE x=VALUES(x), y=VALUES(y), z=VALUES(z)

for whatever columns you wanted to insert.

If you really just wanted to insert the values that you had specified for the various columns, then leave out the VALUES(); you could just do it like this:

INSERT INTO `generic_client_data` (id, keyword, client_id, desc_id) 
VALUES (NULL, 'qqqq', 115, 0) ON DUPLICATE KEY 
UPDATE keyword='qqqq', client_id=115, desc_id=0

However, this requires you to enter all the values twice, and every time you change the statement you'll have to make sure everything matches up.

It wouldn't hurt to read the manual, as the error message suggests: http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜