2016-11-18 109 views
0

我有,我希望通過自然加入加入兩個SQL語句,但由於某些原因,以下是給我的錯誤:加入兩個選擇語句SQL

(select city_name 
from city 
left join country 
on country.country_name=city.country_name 
where country.continent='Europe' 
and city.iscapitol='yes') 

natural join 

(select city_name 
from city 
left join country 
on country.country_name=city.country_name 
where country.continent='Europe' 
and city.iscapitol='no';) 

我使用的是Oracle平臺和錯誤時投擲是:

natural join 
* 
ERROR at line 7: 
ORA-00933: SQL command not properly ended 

這個錯誤會出現什麼原因?任何幫助將不勝感激。

回答

1
select * from (
(select city_name 
from city 
left join country 
on country.country_name=city.country_name 
where country.continent='Europe' 
and city.iscapitol='yes') 

natural join 

(select city_name 
from city 
left join country 
on country.country_name=city.country_name 
where country.continent='Europe' 
and city.iscapitol='no')) 

我刪除了;並添加了外部查詢。我還建議通過明確的條件join

with eurcities as (select city_name, iscapitol, country_name from city 
     left join country on country.country_name=city.country_name 
     where country.continent='Europe') 
select c1.city_name, c2.city_name, c1.country_name 
    from eurcities c1 inner join eurcities c2 on (c1.country_name = c2.country_name) 
    where c1.iscapitol = 'yes' and c2.iscapitol = 'no'; 

更換natural join沒有with它看起來像:

select c1.city_name, c2.city_name, c1.country_name 
    from (select city_name, iscapitol, country_name from city 
      left join country on country.country_name=city.country_name 
      where country.continent='Europe') c1 
    inner join (select city_name, iscapitol, country_name from city 
      left join country on country.country_name=city.country_name 
      where country.continent='Europe') c2 
    on (c1.country_name = c2.country_name) 
    where c1.iscapitol = 'yes' and c2.iscapitol = 'no'; 
+0

@Sal請編輯您的問題,並添加您的表格結構和一些示例數據。使用查詢 – Kacper

+0

@Sal爲您提供建議會容易得多,我編輯了答案並添加了建議的查詢。請試試 – Kacper

+0

'with'子句定義稍後在查詢中使用的數據。您可以考慮這個問題,就像僅針對一個查詢定義的視圖一樣。這會準備僅包含歐洲城市的數據。 'c1'和'c2'只是在'with'子句中定義的表的別名。 @Sal – Kacper

0

首先,忘掉natural join。這是一個等待發生的錯誤。在代碼中不顯示join鍵是危險的。忽略已聲明的外鍵關係是不明智的。依靠命名約定很尷尬。

您可以使用using來編寫此內容。因此,固定的語法,這看起來像:

select * 
from (select city_name 
     from city left join 
      country 
      on country.country_name = city.country_name 
    where country.continent='Europe' and city.iscapitol = 'yes' 
    ) cc join 
    (select city_name 
    from city left join 
      country 
      on country.country_name = city.country_name 
    where country.continent = 'Europe' and city.iscapitol='no' 
    ) cnc 
    using (city_name); 

注意,left join S IN子查詢是不必要的。

這麼說,我覺得聚集是一個更簡單的方法來查詢:

 select city_name 
     from city join 
      country 
      on country.country_name = city.country_name 
     where country.continent = 'Europe' 
     having sum(case when city.iscapitol = 'yes' then 1 else 0 end) > 0 and 
      sum(case when city.iscapitol = 'no' then 1 else 0 end) > 0; 

或者,如果iscapitol [原文]只需要兩個值,您可以使用此爲having條款:

 having min(city.iscapitol) <> max(city.iscapitol)