[英]Join two select statements 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
出現此錯誤的原因是什么? 任何幫助將不勝感激。
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
條件替換natural join
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';
如果沒有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';
首先,不學習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是不必要的。
就是說,我認為聚合是一種更簡單的查詢方法:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.