2015-11-24 44 views
0
insert into airports(country_id) 
select country_id 
from countries 
where countries.country_name = flight_all.dep_country 

這個簡單的代碼無法編譯,因爲sql沒有看到flight_all表。我怎樣才能讓它可見(沒有任何額外的'來自'關鍵字)?SQL代碼不能看到某個表

+1

你的rdbms是什麼? –

回答

3

你應該谷歌SQL JOIN

你可能想DISTINCT避免重複插入

insert into airports(country_id) 
select distinct country_id 
from countries 
join flight_all 
    ON countries.country_name = flight_all.dep_country 
0

因爲flight_all未在查詢中定義。您需要在FROM條款中標識您的表格。使用您目前的做法,它會是這個樣子:

select country_id 
from countries, flight_all 
where countries.country_name = flight_all.dep_country 

然而,注意,這句法被認爲是相當草率的(並且取決於RDBMS甚至不建議使用)。相反,使用JOIN而不是WHERE子句來執行JOIN邏輯。類似這樣的:

select country_id 
from countries 
inner join flight_all 
on countries.country_name = flight_all.dep_country 
+0

不推薦第一個版本,因爲已經考慮過時了。請注意,順便提一下,隱式連接(在from子句中有兩個表)是不推薦的語法,建議切換到現代的顯式語法: 瞭解如何使用顯式連接語法。亞倫伯特蘭做了一些[**寫作**](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx)關於它 –