代码之家  ›  专栏  ›  技术社区  ›  guigui42

Oracle联接使用+子查询:ora-00904字符串:无效标识符

  •  4
  • guigui42  · 技术社区  · 16 年前

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

    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)
    

    此查询将不会提供预期的结果。

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

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

    但是在WHERE子句中,是否可以将“join/using”与子查询组合在一起?

    编辑:使用Oracle 10GR2

    2 回复  |  直到 16 年前
        1
  •  3
  •   Tony Andrews    16 年前

    有趣的问题!在使用时我能管理的最好方法是:

    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)
    
        2
  •  1
  •   Quassnoi    16 年前

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

    此查询:

    select 1 from table4 t4 where t4.pk1 = pk1
    

    正在被分析为

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

    NOT EXISTS 如果在 table4 .

    只需使用显式 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
            )
    
    推荐文章