Sql 对2个表使用Insert/Update-Oracle Apex
我还是SQL新手,在Oracle Apex(使用SQL)中很难弄清楚如何从一个表更新并插入到另一个表中 这两个表被命名为Temp和Table(示例),它们都有相同的列。基本上,它们是彼此的副本,但数据不同。我想将Temp中的ID字段与表中的ID字段进行比较,如果有一行与Temp中的ID字段匹配,则使用Temp中相应行中的数据覆盖表中行中的所有数据 注:表中有1000万行数据,Temp大约有500行Sql 对2个表使用Insert/Update-Oracle Apex,sql,database,oracle,insert,oracle-apex,Sql,Database,Oracle,Insert,Oracle Apex,我还是SQL新手,在Oracle Apex(使用SQL)中很难弄清楚如何从一个表更新并插入到另一个表中 这两个表被命名为Temp和Table(示例),它们都有相同的列。基本上,它们是彼此的副本,但数据不同。我想将Temp中的ID字段与表中的ID字段进行比较,如果有一行与Temp中的ID字段匹配,则使用Temp中相应行中的数据覆盖表中行中的所有数据 注:表中有1000万行数据,Temp大约有500行 if Temp.ID = Table.ID then update set
if Temp.ID = Table.ID then
update
set
Table.ID = Temp.ID
Table.Address = Temp.Address
else
insert
(Table.ID,
Table.Address)
values
(Temp.ID,
Temp.Address
这基本上就是我想要做的,但不确定如何在SQL中编写它。我已经看到了很多不同的答案,但没有一个真正涉及到两个表,而且主要是针对MySQL或SQL Server特定的SQL,我不确定这些SQL是否也适用于Oracle
MERGE into TEST1
USING TEST2 on (TEST2.ID = TEST1.ID)
WHEN matched THEN UPDATE
SET TEST1.ID = TEST2.ID, TEST1.NAME = TEST2.NAME, TEST1.ADDRESS = TEST2.ADDRESS, TEST1.EMAIL = TEST2.EMAIL
WHEN not matched THEN INSERT (ID, NAME, ADDRESS, EMAIL) values (TEST2.ID, TEST2.NAME, TEST2.ADDRESS, TEST2.EMAIL);
我尝试了这个,但它给了我一个错误:
ORA-38104: Columns referenced in the ON Clause cannot be updated: "TEST1"."ID"
更新:成功了!
对错误的答案很有帮助,我不知道您不能在update子句中使用id,这现在完全有意义了。也感谢下面的受访者向我解释合并代码。:) 看起来是
MERGE
的理想候选。看看这个例子
示例表和数据:
SQL> create table ttable (id number, address varchar2(20));
Table created.
SQL> create table temp (id number, address varchar2(20));
Table created.
SQL> insert into ttable
2 select 1, 'Address 1' from dual union all
3 select 2, 'Address 2' from dual union all
4 select 3, 'Address 3' from dual;
3 rows created.
SQL> insert into temp
2 select 1, 'New address 1' from dual union all
3 select 2, 'New address 2' from dual union all
4 select 4, 'New address 4' from dual;
3 rows created.
合并&结果:
SQL> merge into ttable a
2 using temp e on (e.id = a.id)
3 when matched then update set a.address = e.address
4 when not matched then insert (id, address) values (e.id, e.address);
3 rows merged.
SQL> select * from ttable;
ID ADDRESS
---------- --------------------
1 New address 1
2 New address 2
3 Address 3
4 New address 4
SQL>
出于教育目的/我的充分理解,您能否解释一下“ttable a”和“temp e”是什么意思,以及为什么不只是标记(temp.id=ttable.id)?这些只是表别名,用于缩短或缩写表名。(temp.id=ttable.id)也应该可以工作。