ANSI SQL 问题 - 如果记录已存在,如何插入或更新记录?

2024-04-19

虽然我(目前)使用 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)

长期以来,此操作需要两个单独的命令以及一些框架来处理它。因此名称为 UPSERT(UPdate 或 inSERT)。但某些 DBMS 的最新版本支持更优雅的解决方案。

ANSI 标准定义MERGE 语法 http://en.wikipedia.org/wiki/Merge_%28SQL%29。 Oracle 从版本 9i 开始支持这一点,MS SQL Server 从 2005 年开始支持这一点。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)
/

我认为 MERGE 语句主要被设想为一种数据迁移工具,因此它的语法要求我们在 USING 子句中从表中选择数据。我们可以通过从行生成设备(例如 Oracle 中的 Dual)选择文字和伪列来绕过此限制。

MySQL 的语法略有不同,插入...重复密钥更新 http://blog.mclaughlinsoftware.com/2009/05/25/mysql-merge-gone-awry/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ANSI SQL 问题 - 如果记录已存在,如何插入或更新记录? 的相关文章

随机推荐