2015-03-13 92 views
0
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然後保存所有的姓氏。 我的要求是這兩個查詢一起運行,並且希望結果會是怎樣

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_idtable_2

回答

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 
+0

你這是什麼意思ordering_col? – 2015-03-13 11:15:03

+1

'ordering_col'的perpose是爲了確保'first_name'總是在'last_name'前面。 – Houari 2015-03-13 11:16:25

+0

插入的順序無關緊要,因爲表中的行沒有排序順序。因此,'orders_col'是無用的 – 2015-03-13 11:55:08

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