2009-11-25 126 views
4

IM具有我的查询一点语法问题(简化):甲骨文JOIN USING +子查询:ORA-00904字符串:无效标识符

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) 

通过使用 “使用” 关键字时,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子句中将“连接/使用”与子查询结合在一起?

编辑:使用Oracle 10gR2

回答

3

有趣的问题!同时仍然使用使用我可以管理的最好的是:

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) 
+0

事实上,这是要做到这一点,而不完全避免使用的唯一方法(我个人更喜欢坚持JOIN..ON而不是使用)。 – 2009-11-26 04:11:52

1

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

这个查询:

select 1 from table4 t4 where t4.pk1 = pk1 

被解析为

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

NOT EXISTS如果有,但table4一个记录了它始终返回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 
     )