MySQL ON DUPLICATE KEY UPDATE问题

时间:2011-03-08 00:05:43

标签: php mysql

嗨,有人可以看看这个并告诉我哪里出错了。 我有一个SQL语句,当我使用php回应时,我将其设为屏幕

INSERT INTO 'moviedb'.'genre' SET 'GenreID' = '18' , 'GenreName' = 'Drama' ON DUPLICATE KEY UPDATE 'GenreName' = 'Drama' WHERE 'GenreID' = '18'
INSERT INTO 'moviedb'.'genre' SET 'GenreID' = '16' , 'GenreName' = 'Animation' ON DUPLICATE KEY UPDATE 'GenreName' = 'Animation' WHERE 'GenreID' = '16'

这是声明

$sql="INSERT INTO 'moviedb'.'genre' SET 'GenreID' = '{$genresID[$i]}' , 'GenreName' = '{$genreName[$i]}' ON DUPLICATE KEY UPDATE 'GenreName' = '{$genreName[$i]}' WHERE 'GenreID' = '{$genresID[$i]}'";

这是我收到的错误:

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 ''moviedb'.'genre' SET 'GenreID' = '18' , 'GenreName' = 'Drama' ON DUPLICATE KEY ' at line 1

非常感谢任何帮助,提前谢谢。

3 个答案:

答案 0 :(得分:9)

您无法将WHEREON DUPLICATE KEY合并。

删除WHERE子句,MySql只会更新导致重复键的行。

对于多行INSERT,使用VALUES()告诉MySql更新要插入的值,例如:

INSERT INTO moviedb.genre (GenreID,GenreName)
VALUES ('18', 'Drama'),
    ('16', 'Animation')
ON DUPLICATE KEY UPDATE
  GenreName = VALUES(GenreName);

答案 1 :(得分:3)

您正在引用mysql字段...

你应该使用反引号(`)而不是单引号...单引号用于值,反引号用于字段。

INSERT INTO `moviedb`.`genre` SET `GenreID` = '18' , `GenreName` = 'Drama' ON DUPLICATE KEY UPDATE `GenreName` = VALUES(`GenreName`);
INSERT INTO `moviedb`.`genre` SET `GenreID` = '16' , `GenreName` = 'Animation' ON DUPLICATE KEY UPDATE `GenreName` = VALUES(`GenreName`);

答案 2 :(得分:1)

INSERT INTO `moviedb`.`genre` SET `GenreID` = '18' , `GenreName` = 'Drama' ON DUPLICATE KEY UPDATE `GenreName` = 'Drama' WHERE `GenreID` = '18'
INSERT INTO `moviedb`.`genre` SET `GenreID` = '16' , `GenreName` = 'Animation' ON DUPLICATE KEY UPDATE `GenreName` = 'Animation' WHERE `GenreID` = '16'

你已经完成了。