2013-12-13 82 views
2

有沒有基於多行查詢結果插入行的方法?MySQL(SQLite):基於多行查詢插入行結果

像這樣:

For each row in (select brand, date from table_A where ...) insert into table_B (field_1, field_2) VALUES (table_A.brand, table_A.date); 

使用sqlite3的(優選的)/ MySQL的。

感謝

這是我已經試過:

insert into media_tags (fk_id_media, fk_id_tag) VALUES ((select id_media from media where fullpath like "%C32%") , (select id_tag from tags where tagname='digital')) 

回答

3

只要做到:

insert into table_B (field_1, field_2) 
select brand, date 
from table_A 
where... 

這將表-B插入從SELECT返回的所有行。

你的情況,你可以改變::

insert into media_tags (fk_id_media, fk_id_tag) 
values (
    (
    select id_media 
    from media 
    where fullpath like "%C32%" 
    ), (
    select id_tag 
    from tags 
    where tagname = 'digital' 
    ) 
) 

insert into media_tags (fk_id_media, fk_id_tag) 
select id_media, (
    select id_tag 
    from tags 
    where tagname = 'digital' 
    ) 
from media 
where fullpath like "%C32%" 

這將雖然只給你fk_id_media變量值。 fk_id_tag將永遠是相同的,但它看起來像你想要的那樣。

+0

@Azevedo。是的,它的作品。在sqlite和mysql:sqlite演示,mysql演示。 'INSERT .. Values()'可以讓你一次只插入一行,使它適用於多行,這是你的方式。 –

+0

好吧,它可以** **一個選擇**,但如果您使用**兩個選擇**它不會 – Azevedo

+0

當然。這將不起作用,您將不得不使用連接兩個選擇的方式,並只返回一個選擇中的數據。你可以顯示你正在試圖做這個表的表schemmas嗎? –