我什么时候使用嵌套查询postgresql?

时间:2011-02-05 10:25:01

标签: sql nested-query

是什么区别..

select a.value1
from apple a, banana b, oranges o
where a.value1 = b.value1 and o.value1 = a.value1 and o.value2 = 'oranges';

compared to

select a.value1
from apple a
where a.value1 in (
   select b.value1
   from banana b, oranges o
   where b.value1 = o.value1 and o.value2 = 'oranges';
);

真的有区别吗?

2 个答案:

答案 0 :(得分:1)

第一个 MAY 显示表a中的值多次,如果连接条件为x b x c导致多行。

第二个只显示一次表中的值(因为它测试它是否“在子查询的列表中”)

由于您刚刚开始使用SQL,因此请允许我使用ANSI SQL92语法重新编写查询,并使用EXISTS子句替代IN(但可能会以不同方式进行优化)

select a.value1
from apple a
where EXISTS (
   select *
   from oranges o
   INNER JOIN banana b on b.value1 = o.value1
   where o.value2 = 'oranges' and o.value1 = a.value1
);

答案 1 :(得分:0)

是的,存在差异:

如果b和o的连接返回多个具有相同b.value1的行,则第一个查询也将返回多行。但是,第二个查询将所有b.value1放入一个集合中,因此重复的b.value1将被统一。