2017-04-04 77 views
0

我想在一個查詢中添加多行到一個表中,並且我想要插入的一些值來自不同的表。我怎麼做?這裏的sql語句我想放在一起的想法:如何在MySQL中使用不同的select子查詢在表中插入行?

INSERT INTO 
    finalTable (oneID, twoID, oneName, twoNAme, formValue) 
VALUES 
    ('1','a', SELECT oneName FROM tableOne WHERE id = '1' , SELECT twoName FROM tableTwo WHERE id = 'a', 'some value'), 
    ('2','b', SELECT oneName FROM tableOne WHERE id = '2' , SELECT twoName FROM tableTwo WHERE id = 'b' ,'some other value') 

選擇子查詢沒有這種格式的工作,我該如何重新寫的聲明?

回答

0

試試這個解決方案。這可能適用於您的方案。

INSERT INTO finalTable(oneID,twoID,oneName,twoNAme,formValue)

SELECT * FROM (SELECT T1.id,T2.Id,T1.oneName,T2.twoName, 'some value' FROM tableOne T1 LEFT OUTER JOIN tableTwo T2 ON T2.id>0 WHERE T1.id = '1' AND T2.id='a' LIMIT 1) A 

UNION 
SELECT * FROM (SELECT T1.id,T2.Id,T1.oneName,T2.twoName, 'some other value' FROM tableOne T1 LEFT OUTER JOIN tableTwo T2 ON T2.id>0 WHERE T1.id = '2' AND T2.id='b' LIMIT 1) B 
相關問題