开发者

When do I use a nested query for postgres sql?

whats the difference between..

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

co开发者_JAVA百科mpared 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';
);

is there really a difference?


The first one MAY show values from table a more than once, if the join conditions a x b x c result in multiple rows.

The second one will only show values from the table a once (since it tests to see if it is "in the list from the subquery")

Since you are just starting out with SQL, allow me to rephrase your query using ANSI SQL92 syntax, and also the EXISTS clause which is the alternative to IN (but may optimize differently)

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
);


Yes, there is a differences:

If the join of b and o returns multiple rows with the same b.value1, the first query will return multiple rows, too. The second query, however, puts all the b.value1 into a set, so duplicated b.value1 will be unified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜