虽然我正在使用mySQL(目前),但我不想要任何特定于数据库的SQL.
我试图插入一个记录,如果它不存在,并更新一个字段,如果它存在.我想使用ANSI SQL.
该表看起来像这样:
create table test_table (id int, name varchar(16), weight double) ;
//test data
insert into test_table (id, name, weight) values(1,'homer', 900);
insert into test_table (id, name, weight) values(2,'marge', 85);
insert into test_table (id, name, weight) values(3,'bart', 25);
insert into test_table (id, name, weight) values(4,'lisa', 15);
If the record exists, I want to update the weight (increase by say 10)
Run Code Online (Sandbox Code Playgroud)
很长一段时间,这个操作需要两个单独的命令以及一些框架来处理它.因此名称为UPSERT(UPdate或inSERT).但是最新版本的某些DBMS支持更优雅的解决方案.
ANSI标准定义了MERGE语法.自9i版以来,Oracle一直支持这种方式,自2005年以来,它在MS SQL Server中得到了支持.MERGE语句可能有点冗长.
merge into t23
using t42
on t42.id = t23.id
when matched then
update
set t23.col1 = t42.col1
when not matched then
insert (id, col1)
values (t42.id, t42.col1)
/
Run Code Online (Sandbox Code Playgroud)
我认为MERGE语句主要被设想为数据迁移工具,因此它的语法要求我们在USING子句中从表中选择数据.我们可以通过从行生成设备(例如Oracle中的dual)中选择文字和伪列来解决此限制.
MySQL的语法略有不同,INSERT ... ON DUPLICATE KEY UPDATE.