【问题标题】:UNION and NOT EXISTS throws ErrorUNION 和 NOT EXISTS 抛出错误
【发布时间】:2018-03-01 13:40:01
【问题描述】:

我有一个表,其中包含英文和法文名称的城市名称,只有名称不同,否则它将只有英文名称。 笔记。城市 CityA 和 CityA` 的地理编码相同,因为两者是同一个城市,但编码不同。

表名=城市

列在下面

city,code,language,geocode

例如。

cityA  Frc
cityA  Frc
cityB  Eng
CityC  Eng
CityD  Eng
CityD` FRC

所以我们可以从上面的例子中看到 CityA 有法语和英语名称,而 CityB 没有,因为 CityB 在法语和英语中都有相同的拼写 /accent。

我要做的是基于用户语言,如果用户语言是法语,则返回所有法语名称加上没有法语口音的英语名称。 所以从上面它应该返回 CityA`,CityB,CityC,CityD'

类似地,如果用户语言是英文,则返回所有英文名称。 城市A,城市B,城市C.城市D。

以下是我尝试过的

select a.city,a.code from country a
where a.language=userenv('lang') -- it will be either french or english 
union
select b.city,b.code from country b
where b.language='Eng' 
AND not exists( select geocode from country 
            where geocode = a.geocode)

我收到错误,因为 a.geocode 未识别。

【问题讨论】:

    标签: sql oracle union


    【解决方案1】:

    您需要正确的表别名。

    我会推荐:

    select c.city, c.code
    from country c
    where c.language = userenv('lang') -- it will be either french or english 
    union all
    select c2.city, c2.code
    from country c2
    where c2.language = 'Eng' and
          not exists (select 1
                      from country c3
                      where c3.geocode = c2.geocode
                     );
    

    在您的查询中,a 的别名在子查询中未知。但是,表别名应该是表名的缩写,而不是任意字母。

    也就是说,我认为您真正想要的查询是:

    select c.city, c.code
    from country c
    where c.language = userenv('lang') -- it will be either french or english 
    union all
    select c2.city, c2.code
    from country c2
    where c2.language = 'Eng' and
          not exists (select 1
                      from country c3
                      where c3.geocode = c2.geocode and
                            c3.language = userenv('lang')
                     );
    

    【讨论】:

    • 您的第一个查询无法运行,因为 NOT EXISTS 将排除所有行。它是同一张表,因此该地理编码始终有一行,即 current 行。
    【解决方案2】:

    做一个自我full outer join,一个表实例用于userenv('lang'),一个用于英文:

    select coalesce(c1.city, c2.city), coalesce(c1.code, c2.code)
    from country c1
    full outer join country c2
       on  c1.code = c2.code 
       and c1.language = userenv('lang')
       and c2.language = 'Eng'
    

    使用COALESCE() 选择userenv('lang') 值(如果可用),否则选择英文值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 2022-06-16
      • 2013-07-07
      • 2012-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多