我在 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 中有相同的东西吗?
最佳答案
INSERT ... ON DUPLICATE KEY UPDATE在 MySQL 中提供更简单的语法,还通过受影响的行 API 调用向您提供有关发生的情况的反馈。根据我的经验,很少有人意识到知道以下内容对您的程序逻辑有多么方便:
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values.
关于c# - Mysql如果存在则更新否则插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15100809/