我有两个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
这个错误会出现的原因是什么?任何帮助将不胜感激。
答案 0 :(得分: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'))
我已删除;
并添加了外部查询。我还建议您使用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';
答案 1 :(得分: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
是不必要的。
那就是说,我认为聚合是一种更简单的查询方法:
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
[sic]只接受两个值,则可以将其用于having
子句:
having min(city.iscapitol) <> max(city.iscapitol)