我有一个表TABLE101,其中包含以下字段:
COL1 COLB COLC COLD
ACT1 UYT 876 KJH
ACT2 CFG 976 TRY
我有另一个表TABLE102,如下所示:
COL1 COL2 COL3 COL4 COL5 COL6
ACt1 A1_B1 98 UI 2
ACT2 C1 00 N
ACT2 D1_D4 1 PP Y RT
ACT2 A1_F1 9T UI 2
现在我想将数据插入到第3个表中,该表包含table101和表102中的所有字段,如:
COL1 COLB COLC COLD COL2 COL3 COL4 COL5 COL6 LVL
ACT1 UYT 876 KJH 1
ACt1 A1_B1 98 UI 2 2
ACT2 CFG 976 TRY 1
ACT2 C1 00 N
ACT2 D1_D4 1 PP Y RT 2
ACT2 A1_F1 9T UI 2 2
所以我需要从table101插入第一行,对于相应的COL1值,我需要从TABLE102插入一行。 在表101中,COL1是唯一的,但在表101中,col1可以有多行。 如果我从table101插入行,我必须将lvl col设置为1,如果我插入表格table102我将lvl col设置为2
我该怎么办?
答案 0 :(得分:0)
您可以使用UNION ALL
来合并表格。然后使用INSERT ... SELECT
语法插入第3个表。
SELECT COL1 , COLB, COLC , COLD, NULL AS COL2, NULL AS COL3, NULL AS COL4, NULL AS COL5, NULL AS COL6, 1 AS LVL FROM TABLE101
UNION ALL
SELECT COL1, NULL AS COLB, NULL AS COLC, NULL AS COLD, COL2, COL3, COL4 , COL5 , COL6 , 2 AS LVL FROM TABLE102
答案 1 :(得分:0)
设定:
create table table101 as
select 'ACT1' col1, 'UYT' colb, 876 colc, 'KJH' cold from dual union all
select 'ACT2' , 'CFG' , 976 , 'TRY' from dual
;
commit;
select * from table101;
COL1 COLB COLC COLD
---- ---- ---- ----
ACT1 UYT 876 KJH
ACT2 CFG 976 TRY
2 rows selected.
create table table102 as
select 'ACT1' col1, 'A1_B1' col2, '98' col3, 'UI' col4, null col5, '2' col6 from dual union all
select 'ACT2' , 'C1' , null , '00' , 'N' , null from dual union all
select 'ACT2' , 'D1_D4' , '1' , 'PP' , 'Y' , 'RT' from dual union all
select 'ACT2' , 'A1_F1' , '9T' , 'UI' , null , '2' from dual
;
commit;
select * from table102;
COL1 COL2 COL3 COL4 COL5 COL6
---- ----- ---- ---- ---- ----
ACT1 A1_B1 98 UI 2
ACT2 C1 00 N
ACT2 D1_D4 1 PP Y RT
ACT2 A1_F1 9T UI 2
4 rows selected.
create table table110 (col1 varchar2(4000), colb varchar2(4000), colc number, cold varchar2(4000),
col2 varchar2(4000), col3 varchar2(4000), col4 varchar2(4000), col5 varchar2(4000),
col6 varchar2(4000), lvl number);
Table TABLE110 created.
插入陈述和结果:
insert into table110
select col1, colb, colc, cold, null, null, null, null, null, 1
from table101
union all
select col1, null, null, null, col2, col3, col4, col5, col6, 2
from table102
;
commit;
select * from table110;
COL1 COLB COLC COLD COL2 COL3 COL4 COL5 COL6 LVL
---- ---- ---- ---- ----- ---- ---- ---- ---- ---
ACT1 UYT 876 KJH 1
ACT2 CFG 976 TRY 1
ACT1 A1_B1 98 UI 2 2
ACT2 C1 00 N 2
ACT2 D1_D4 1 PP Y RT 2
ACT2 A1_F1 9T UI 2 2
6 rows selected.
select * from table110;