带有别名的多个表的SQL“Where exists”

时间:2011-11-17 21:48:37

标签: sql oracle

示例查询:

Select id, id_dtm
From tableA 
Where exists (
 Select 1 
 From tableB b, tableC c, tableD d
 Where b.id = id
 And b.id_dtm = id_dtm
 And b.id = c.id
 And c.id = d.id);

上述查询的问题是所有4个表都有名为id和id_dtm的列。 当我运行它时,我收到一个错误,表示列ORA-00918:列模糊定义

我可以通过在tableA中使用别名来修复,但问题是查询是动态生成的。 where exists部分是在其他地方生成的,稍后合并它之前的位,所以我不能像现在这样使用别名。

有没有办法在where exists子句中使用tableA中的id和id_dtm而不使用tableA的别名?

数据库是Oracle10G

3 个答案:

答案 0 :(得分:6)

写表名tableA

Select id, id_dtm
From tableA 
Where exists (
 Select 1 
 From tableB b, tableC, tableD
 Where tableB.id = tableA.id
 And tableB.id_dtm = tableA.id_dtm
 And tableB.id = tableC.id
 And tableC.id = tableD.id)

答案 1 :(得分:1)

我不知道您的确切设置,但为什么不能在外表上设置别名?它不必反映实际使用的表,只需将其替换为“外部”或其他内容。在内部查询中的用法,你已经知道id存在于外部使用的任何表中,所以outer.id可以正常工作。

答案 2 :(得分:-1)

子查询中引用tableA(即idid_dtm)的字段也存在于其他表中,因此它们不明确。通过为那些使用tableA

的别名添加前缀来解决此问题
Select A.id, A.id_dtm
From tableA A 
Where exists (
 Select 1 
 From tableB b, tableC c, tableD d
 Where b.id = A.id
 And b.id_dtm = A.id_dtm
 And b.id = c.id
 And c.id = d.id);