2014-04-13 123 views
0

我有一張表,我想在其中插入數據,並且值本身必須來自多個表。這必須做如下,通過閱讀MySQL文檔:插入到多個選擇

insert into flight(airlinecompanyId,planetypeId) 
select id from airlinecompany where naam = 'Brussels Airlines', 
select id from planeType where type = 'Boeing 737'; 

所以,簡單地解釋,我想插入的ID從表中的airlinecompany和planetype,我通過地方clausule要求,到飛行表列。

當我嘗試此查詢,我不斷收到以下錯誤:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' select id from planeType where type = 'Boeing 737'' at line 2 

誰的人有一個解決方案嗎?

+1

如何這兩個表('airlinecomapny,planetype')有關嗎?您要插入兩列 - 兩張表的id是否完全相同? –

+0

他們沒有關係,但airlineCompanyId和planetypeId都是航班表中的外鍵,如果這就是你的意思? – Programmer1994

+0

那你的目標是什麼?如果'planeType'和'airlinecompany'不相關,你是否試圖爲這兩個值插入一行? –

回答

2

airlinecompanyplaneType之間沒有任何關係,你不必執行JOIN做插入,但因爲你正在創建僅在flight單行,它可以很容易地使用子查詢完成,包裹每個表的SELECT聲明在()

INSERT INTO flight (airlinecompanyId, planetypeId) 
    SELECT 
    (SELECT id FROM airlinecompany WHERE naam = 'Brussels Airlines'), 
    (SELECT id FROM planeType WHERE type = 'Boeing 737') 
    /* MySQL will permit this with no FROM clause */ 

它可任選被一個CROSS JOIN來完成,因爲只有一種可能返回行:

INSERT INTO flight (airlinecompanyId, planetypeId) 
    SELECT 
    ac.id, 
    pt.id 
    FROM 
    airlinecompany ac 
    CROSS JOIN planeType pt 
    WHERE 
    ac.naam = 'Brussels Airlines' 
    AND pt.type = 'Boeing 737' 
+0

好吧,上面那個是最容易的,做了這個工作! 謝謝! – Programmer1994