做多个左外连接的最佳方法

时间:2012-07-02 02:59:57

标签: sql oracle left-join

我有一个表需要碰撞多个表,左外连接除了右边。这是最好的做法吗?首先联合所有其他表?还有别的吗?

这是我想到的第一个想法,但我想知道是否有更好的方法。

select
    master_table.*
from
    master_table
left outer join
    (
        select customer_id from table_1
        union
        select customer_id from table_2
        union
        select customer_id from table_3
        union
        select customer_id from table_4
    ) bump_table
on
    master_table.customer_id = bump_table.customer_id
where
    bump_table.customer_id is null

2 个答案:

答案 0 :(得分:2)

我认为一个NOT EXISTS会更好。它当然更好地传达了查询的意图。

select * from master_table m
 where not exists( select 1 from table_1 where m.customer_id=table_1.customer_id)
   and not exists( select 1 from table_2 where m.customer_id=table_2.customer_id)
   and not exists( select 1 from table_3 where m.customer_id=table_3.customer_id)
   and not exists( select 1 from table_4 where m.customer_id=table_4.customer_id)

答案 1 :(得分:1)

基本形式肯定更快 - 类似于@dbenham已经提供的NOT EXISTS

SELECT m.*
FROM   master_table m
LEFT   JOIN table_1 t1 ON t1.customer_id =  m.customer_id
LEFT   JOIN table_2 t2 ON t2.customer_id =  m.customer_id
LEFT   JOIN table_3 t3 ON t3.customer_id =  m.customer_id
LEFT   JOIN table_4 t4 ON t4.customer_id =  m.customer_id
WHERE  t1.customer_id IS NULL
AND    t2.customer_id IS NULL
AND    t3.customer_id IS NULL
AND    t4.customer_id IS NULL;