SQL - '存在'没有平等检查的条款

时间:2014-03-18 17:06:09

标签: sql oracle oracle11g oracle10g

有人可以解释这种语法的作用:

where exists(select * from table(source.sources)) 

我不明白比较是如何进行的。我习惯的语法是

Select x
from y
where exists (select 1 from z where z.id = y.id)

在第一个存在语句中,y.id = x.id比较发生在哪里?我能看到第一种语法如何使用的例子吗?

由于

1 个答案:

答案 0 :(得分:3)

看起来sourcessource表中的嵌套表。这是一个例子:

create type sources_type as table of number
/

create table source (id number, sources sources_type)
nested table sources store as sources_tab;

insert into source (id, sources) values (1, null);
insert into source (id, sources) values (2, sources_type());
insert into source (id, sources) values (3, sources_type(1, 2, 3));

三行是sources的三种可能状态; null,一个空表(不是同一个东西)和一个填充表。如果要选择表不为空的行,则无法检查它是否为空,因为这只是故事的一半。

select * from source
where sources is null;

        ID SOURCES                                
---------- ----------------------------------------
         1                                          

select * from source
where sources is not null;

        ID SOURCES                                
---------- ----------------------------------------
         2 STACKOVERFLOW.SOURCES_TYPE()             
         3 STACKOVERFLOW.SOURCES_TYPE(1,2,3)        

您可能不希望包含id=2的行。因此,您可以查看嵌套表格内容:

select * from source
where not exists (select * from table(sources));

        ID SOURCES                                
---------- ----------------------------------------
         1                                          
         2 STACKOVERFLOW.SOURCES_TYPE()             

select * from source
where exists (select * from table(sources));

        ID SOURCES                                
---------- ----------------------------------------
         3 STACKOVERFLOW.SOURCES_TYPE(1,2,3)        

因此,最终查询忽略空嵌套表以及空值。

在你的第二个例子中,你正在做一个相关的子查询(或者至少我假设如果伪代码有点受损),寻找不属于主查询的表中的匹配数据, (通常)需要进行相等测试;在第一个例子中,您正在检查同一个表中是否存在数据,因此无需进行比较。

您也可以检查嵌套表中的特定值 - 我不确定这是否澄清或混淆了问题:

select * from source
where exists (select * from table(sources) where column_value = 2);