我想创建一个类似于INSERT IF NOT EXISTS ELSE UPDATE的SQL查询。
我发现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);任何帮助或建议都是非常感谢的。
发布于 2015-02-04 14:42:32
您漏掉了这里中的下列句子
“非限定源表名称(或其相关名称)可能与不合格目标表名称(或其相关名称)不相同。”
这意味着您不能同时使用一个表作为源和目标!
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 发布于 2015-01-30 13:07:14
您没有将表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';https://stackoverflow.com/questions/28235892
复制相似问题