【问题标题】:Oracle JOIN USING + Subquery : ora-00904 string: invalid identifierOracle JOIN USING + 子查询:ora-00904 字符串:无效标识符
【发布时间】:2010-12-20 08:17:56
【问题描述】:

我的查询中有一点语法问题(简化):

select *
from table1 t1
inner join table2 t2 using (pk1)
inner join table3 t3 using (pk2)
where not exists (select1 from table4 t4 where t4.pk1 = t1.pk1)

通过使用“using”关键字,oracle不允许在列名前面加上表标识符(例如:t1.pk1,只能使用pk1)

如果我写:

select *
from table1 t1
inner join table2 t2 using (pk1)
inner join table3 t3 using (pk2)
where not exists (select1 from table4 t4 where t4.pk1 = pk1)

此查询不会给出预期的结果。

但由于我使用的是“存在”子查询,我该如何加入这个子查询?

当然,我想我可以用另一种方式编写此查询并避免存在,或者我不能使用“使用”。

但是是否可以在 where 子句中将“join / using”与子查询结合使用?

编辑:使用 Oracle 10gR2

【问题讨论】:

    标签: oracle syntax join exists ora-00904


    【解决方案1】:

    有趣的问题!在使用 USING 时我能做到的最好的方法是:

    select * from
    ( select *
      from table1 t1
      inner join table2 t2 using (pk1)
      inner join table3 t3 using (pk2)
    ) v
    where not exists (select1 from table4 t4 where t4.pk1 = v.pk1)
    

    【讨论】:

    • 确实,这是在不完全避免使用的情况下做到这一点的唯一方法(我个人更喜欢坚持使用 JOIN..ON 而不是使用)。
    【解决方案2】:

    您不能将表限定符与自然连接一起使用。

    这个查询:

    select 1 from table4 t4 where t4.pk1 = pk1
    

    被解析为

    select 1 from table4 t4 where t4.pk1 = t4.pk1
    

    如果table4 中只有一条记录,则NOT EXISTS 总是返回false。

    只需使用明确的JOIN 条件:

    WITH    table1 AS
            (
            SELECT  1 AS pk1
            FROM    dual
            ),
            table2 AS
            (
            SELECT  1 AS pk1, 1 AS pk2
            FROM    dual
            ),
            table3 AS
            (
            SELECT  1 AS pk2
            FROM    dual
            ),
            table4 AS
            (
            SELECT  2 AS pk1
            FROM    dual
            )
    SELECT  *
    FROM    table1 t1
    JOIN    table2 t2
    ON      t2.pk1 = t1.pk1
    JOIN    table3 t3
    ON      t3.pk2 = t2.pk2
    WHERE NOT EXISTS
            (
            SELECT  1
            FROM    table4 t4
            WHERE   t4.pk1 = t1.pk1
            )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-12
      • 2019-06-21
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多