我是Sql server我使用此命令插入值,如果id已经存在,则更新该值
string commandLine = "IF NOT EXISTS(SELECT clientid FROM Rating WHERE clientid = " + clientId + " AND userid = " + userid + ") " +
"INSERT INTO Rating VALUES(@clientId,@userid,@rating) " +
"ELSE " +
"UPDATE Rating SET rating=@rating WHERE clientid = " + clientId + " AND userid = " + userid + ";";
我现在转到MySQL
,这个命令不起作用。 MySQL中有什么相同的东西吗?
答案 0 :(得分:7)
INSERT ... ON DUPLICATE KEY UPDATE提供了MySQL中的等效语法。
答案 1 :(得分:1)
如果您在clientid上有唯一约束或主键,则可以使用INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO Rating VALUES(@clientId,@userid,@rating)
ON DUPLICATE KEY
UPDATE Rating SET rating=@rating