从sql中的select语句插入多行

时间:2016-10-21 03:36:52

标签: sql oracle select insert

我有一张表需要迁移到新表。

表A迁移到表B

表A

| ID   | type |

| A1   |  A   |
| A2   |  B   |
| A3   |  A   |
| A4   | both |
| A5   |  A   |

我希望表B看起来像这样

表B

| ID   | FKA  |  TYPE |

| B1   |  A1  |   Aa  |
| B2   |  A2  |   Bb  |
| B3   |  A3  |   Aa  |
| B4   |  A4  |   Aa  |
| B5   |  A4  |   Bb  |
| B6   |  A5  |   Aa  |

如果你意识到如果type是两者,它将在表A中从表A中插入两次。

** FKA是表A中的外键

目前我做了3次查询

查询1:

insert into tableB
select sequence1.nextVal, ID, 
(case
when type = 'A' then 'Aa'
when type = 'B' then 'Bb'
when type = 'both' then 'Aa'
else NULL
end
) from tableA

查询2

insert into tableB
select sequence1.nextVal, ID, 
(case
when type = 'both' then 'Bb'
else 'laterdelete'
end
) from tableA

查询3

delete from tableB where type = 'laterdelete'

谢谢你们

2 个答案:

答案 0 :(得分:1)

我认为rdbms是Oracle。您可能想要使用这些值

创建一个表(例如“tablemapping”)
 FieldFrom FieldTo
 A         Aa
 B         Bb
 both      Aa
 both      Bb

所以你可以做到:

 Insert into tableB
 select sequence1.nextval, ID, FieldTo
    FROM tableA a 
         join tablemapping m 
           on a.type=m.fieldFrom

如果您不想拥有映射表,可以模拟一个映射表。

 Insert into tableb
 select sequence1.nextval, ID, FieldTo
    FROM tableA a 
         join (
               select 'both'  as FieldFrom,  'Ab'  as FieldTo from dual
                Union all
               select 'both'  as FieldFrom,  'Bb'  as FieldTo from dual
                Union all
               select 'A'  as FieldFrom,  'Aa'  as FieldTo from dual
                Union all
               select 'B'  as FieldFrom,  'Bb'  as FieldTo from dual
              ) tablemapping m 
           on a.type=m.fieldFrom

答案 1 :(得分:0)

您可以在第一个查询中使用union来在tableB中获得所需的结果。 查询如下:

insert into tableB
select sequence1.nextVal, ID, 
(case
when type = 'A' then 'Aa'
when type = 'B' then 'Bb'
when type = 'both' then 'Aa'
else NULL
end
) from tableA
UNION
select sequence1.nextVal, ID, 
(case
when type = 'A' then 'Aa'
when type = 'B' then 'Bb'
when type = 'both' then 'Bb'
else NULL
end
) from tableA

当tableA中的type都存在时,上面的查询将在tableB中插入Aa和Bb。 希望这会有所帮助。