2

我有一张表,我需要碰到多个表,其中左外连接不包括右外连接。对此有最佳做法吗?先联合所有其他表?还有什么?

这是我想到的第一个想法来处理这个问题,但我想知道是否有更好更有效的方法。

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
4

2 回答 2

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)
于 2012-07-02T03:14:11.330 回答
1

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

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;
于 2012-07-02T05:35:31.987 回答