Subquery or join?

Some tasks can be performed in two ways, both by joins and subqueries. Under what situations should we opt for subqueries?

Write your query using a subquery instead of a join when it is easier for you to understand what the purpose or intent of the query is. Remember, you not only have to write it, you may have to come back six months later and figure out what it's doing! I'll demonstrate with two examples:
Example 1

Do you prefer:

select a.foo, a.bar
from table1 a
inner
join table2 b
on a.id = b.id
and b.qux = '937'
group
by a.foo, a.bar

or:

select foo, bar
from table1
where id in
( select id
from table2
where qux = '937' )

Example 2

Do you prefer:

select a.foo, a.bar
from table1 a
left outer
join table2 b
on a.id = b.id
and b.qux = '937'
where b.id is null

or:

select foo, bar
from table1
where not exists
( select 1
from table2
where id = table1.id
and qux = '937' )

Ordinarily, when writing SQL, you should not be concerned with performance. Instead, you should focus all your intellect on ensuring that you get the correct results, and let the database optimizer figure out how to satisfy the query. So the first consideration is whether the join and subquery techniques actually do both produce the same correct results in either example.

The other consideration is maintainability. The first example returns rows from table1 with matching qualified rows in table2, while the second example returns only rows without qualified matches. Now consider how you would have to modify each query in both examples to add another condition, to return only those rows from table1 that also have a qualifying matching row in table3. You may discover that the join technique is severely limiting.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值