繁体   English   中英

连接两个select语句sql

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM