我想创建一个类似INSERT IF NOT EXISTS ELSE UPDATE
我发现Derby能够MERGE
,我试图用它来解决我的问题。
MERGE INTO test_table a
USING test_table b
ON a.city = 'foo'
WHEN NOT MATCHED THEN INSERT values ( 'foo', '2012-11-11', 'UK')
WHEN MATCHED AND a.modification_date > '1111-11-11' THEN
UPDATE SET a.modification_date = '2012-11-11',
a.city = 'foo1',
a.country = 'US'
上述声明给出了以下错误:
Error code 30000, SQL state 23505: The statement was aborted because it
would have caused a duplicate key value in a unique or primary key
constraint or unique index identified by 'SQL150129144920080' defined on 'test_table'
我怎么能运行以下声明:
INSERT INTO test_table values ( 'foo', '2012-11-11', 'UK');
证明上述城市尚未出现在表格中。
我的表包含以下结构:
CREATE TABLE test_table(
city VARCHAR(100) NOT NULL PRIMARY KEY,
modification_date DATE NOT NULL,
country VARCHAR(2) NOT NULL);
非常感谢任何帮助或建议。
答案 0 :(得分:0)
您没有将表a连接到表b,因此查询可能会尝试对表B中的每一行执行插入,假设表B包含城市字段,请尝试
MERGE INTO test_table as a
USING test_table b
ON a.city = b.city and a.city = 'foo'
WHEN NOT MATCHED THEN INSERT values ( 'foo', '2012-11-11', 'UK')
WHEN MATCHED AND a.modification_date > '1111-11-11' THEN
UPDATE SET a.modification_date = '2012-11-11',
a.city = 'foo1',
a.country = 'US';
答案 1 :(得分:0)
您错过了here
中的以下句子"非限定源表名称(或其相关名称)可能与非限定目标表名称(或其相关名称)不同。"
这意味着你不能同时使用一个表作为源和目标!
just one example:
we have two schemas: schema1 and schema2
and two tables: schema1.table1 and schema2.table1
--i have to write all details:
create schema schema1;
create table schema1.table1 (
name varchar(255) not null,
id int not null primary key
);
create schema schema2;
create table schema2.table1 (
name varchar(255) not null,
id int not null primary key
);
--suppose we have inserted some entries into schema2.table1
insert into schema2.table1 values
('foo', 1), ('bar', 2);
--and we want just to copy values from schema2.table1 into schema1.table1
--apply MERGE INTO ... INSERT ...
merge into schema1.table1 as tableTarget
using schema2.table1 as tableSrc
on tableTarget.id= tableSrc.id
when matched then
update set tableTarget.name=tableSrc.name
when not matched then
insert(name, id) values (tableSrc.name, tableSrc.id);
--that has to work