如何逐个执行多个查询

时间:2015-03-13 10:58:28

标签: postgresql

table_1 (id, first_Name, last_Name)

table_2 (id, name, table_1_id)

我的工作是将一个列的所有值从table_1复制到table_2作为单独的条目。我的问题是

QUERY_1:

insert into table_2 ( name, table_1_id )  
   select first_Name as name, id as table_1_id from table_1.

我的其他疑问是

Query_2:

insert into table_2 ( name, table_1_id )  
   select last_Name as name, id as table_1_id from table_1.

它运行得很好,但保存所有first_name然后保存所有last_name。 我的要求是将这两个查询一起运行,并希望结果类似于

first_Name(whatever) table_1_id (1)

last_Name(whatever) table_1_id(1)

first_Name(whatever) table_1_id(2)

last_Name(whatever) table_1_id(2)

提前致谢

注意:table_1_id不是table_2

中的外键

2 个答案:

答案 0 :(得分:0)

您可以使用union all

来实现此目的
INSERT INTO table_2( name, table1_id)
select name, id from
    (
    select first_name as name, id from table_1
    union all
    select last_name as name, id from table_1
    ) A 
    order by id

答案 1 :(得分:0)

尝试使用WITH Queries (Common Table Expressions)

   WITH cte AS (
    insert into table_2 ( name, table_1_id )  
    select first_Name as name, id as table_1_id from table_1
    )
    insert into table_2 ( name, table_1_id )  
    select last_Name as name, id as table_1_id from table_1

并按select * table_2 order by table_1_id

测试值