Sql Derby合并插入不工作
我想创建一个SQL查询,它的工作方式类似于Sql Derby合并插入不工作,sql,javadb,Sql,Javadb,我想创建一个SQL查询,它的工作方式类似于INSERT IF NOT EXISTS ELSE UPDATE 我发现Derby能够合并,我试图用它来解决我的问题 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 >
INSERT IF NOT EXISTS ELSE UPDATE
我发现Derby能够合并
,我试图用它来解决我的问题
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);
非常感谢您提供的任何帮助或建议。您没有将表a连接到表b,因此查询可能会尝试为表b中的每一行执行插入操作,假设表b包含城市字段try
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';
你错过了下面的句子 “非限定源表名(或其关联名)可能与非限定目标表名(或其关联名)不同。” 这意味着您不能同时使用一个表作为源和目标
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
谢谢你的回复。不幸的是,我总是犯同样的错误