Derby Merge 插入不工作

Derby Merge insert not working

我想创建一个 SQL 查询,它的工作方式类似于 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');

证明table中不存在上述城市

我的 table 包含以下结构:

CREATE TABLE test_table(
       city VARCHAR(100) NOT NULL PRIMARY KEY,
       modification_date DATE NOT NULL,
       country VARCHAR(2) NOT NULL);

非常感谢任何帮助或建议。

您没有将 table a 连接到 table b,因此查询可能会尝试对 table B 中的每一行进行插入,假设 table 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';

您错过了 here

中的以下句子

"The unqualified source table name (or its correlation name) may not be the same as the unqualified target table name (or its correlation name)."

这意味着您不能同时使用一个 table 作为源和目标!

            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