2016-11-18 110 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)