4

我想知道如何在 1)样式和 2)性能方面改进这种形式的查询。以防万一,我使用 Oracle 作为我的数据库。此外,此查询的目的是从第一个 select 语句中选择在 LEFT JOIN 右侧的记录集中没有相应记录的所有记录。来自 ColumnA 的记录在任何表中不一定是唯一的。

select ColumnA
from
    (Select ColumnA
    from Table1)
left join
    ((select ColumnA, ColumnB
    from Table2)
    union
    (select ColumnA, ColumnB
    from Table3))
using (ColumnA)
where ColumnB is null
group by ColumnA;

谢谢你。

4

3 回答 3

3

我认为您可以将此查询重写为以下内容(请参阅此SQL Fiddle):

SELECT  DISTINCT ColumnA
FROM    (SELECT  ColumnA
         FROM    Table1)

MINUS

(SELECT  ColumnA
FROM    Table2
UNION
SELECT  ColumnA
FROM    Table3);

至于风格,为了可读性和清晰度,我建议使用显式连接条件语法LEFT JOIN ... ON table1.somecolumn = table2.someothercolumn而不是条件。USING但这很可能是个人喜好:-)

于 2013-03-22T23:36:43.840 回答
3

我认为不需要UNION

select T1.ColumnA
from Table1 T1
    left join Table2 T2 ON T1.ColumnA = T2.ColumnA
    left join Table3 T3 ON T1.ColumnA = T3.ColumnA
where T2.ColumnA IS NULL 
    or T3.ColumnA IS NULL
group by T1.ColumnA;

另一种选择是使用NOT IN

select distinct ColumnA
from Table1 
where ColumnA not in (select ColumnA from Table2) 
    and ColumnA not in (select ColumnA from Table3);

这两个都应该返回 Table1 中不在 Table2 或 Table3 中的任何 ColumnA 记录。

于 2013-03-22T23:20:54.260 回答
2

这里有三种选择。

select distinct ColumnA
  from Table1      a
  left join Table2 b using(ColumnA)
  left join Table3 c using(ColumnA)
 where b.ColumnB is null
   and c.ColumnB is null;

.

select distinct ColumnA
  from Table1 a
 where ColumnA not in(select ColumnA from Table2)
   and ColumnA not in(select ColumnA from Table3);

.

select distinct ColumnA
  from Table1 a
 where ColumnA not in(select ColumnA from Table2 union
                      select ColumnA from Table3);
于 2013-03-22T23:35:20.390 回答