简体   繁体   English

如果特定的列值不同,则更新行,否则插入新行

[英]Update the row if a particular column value differ, else insert new row

I have a table 我有桌子

UserId    Name    Age
1         Lisha   23
2         Ankur   21
3         Karan   22

For a particular given UserId, I want to update the age if the given age is different then the current age. 对于特定的给定UserId,如果给定年龄与当前年龄不同,我想更新年龄。 Else if the UserId doesn't exists I want to insert a new row. 否则,如果UserId不存在,我想插入一个新行。

How can I do this in a single SQL statement. 如何在单个SQL语句中执行此操作。

MySQL has a neat syntax that does exactly that, albeit it goes about it the opposite way - you define what you'd want to insert, and if a duplicate key error is generated, you define how you'd like to update the data instead: MySQL具有一种精巧的语法,可以做到这一点,尽管它采用相反的方式-您定义要插入的内容,如果生成重复的键错误,则可以定义如何更新数据:

INSERT INTO users
(userid, age)
ON DUPLICATE KEY UPDATE age = VALUES(age)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM