如何用LEFT OUTER JOIN等效替换复杂的SQL MINUS查询

时间:2014-01-09 00:54:16

标签: sql outer-join

尝试使用等效的左外连接来计算如何替换以下内容:

select distinct(a.some_value)
from table_a a, table_b b
where a.id = b.a_id 
and b.some_id = 123
and b.create_date < '2014-01-01' 
and b.create_date >= '2013-12-01'  
MINUS
select distinct(a.some_value)
from table_a a, table_b b
where a.id = b.a_id 
and b.some_id = 123 
and b.create_date < '2013-12-01' 

无法执行“NOT IN”,因为第二个查询的数据太多。

3 个答案:

答案 0 :(得分:5)

SELECT * FROM
(
  select distinct(a.some_value)
  from table_a a, table_b b
  where a.id = b.a_id 
  and b.some_id = 123
  and b.create_date < '2014-01-01' 
  and b.create_date >= '2013-12-01'  
) x
LEFT JOIN 
(
  select distinct(a.some_value)
  from table_a a, table_b b
  where a.id = b.a_id 
  and b.some_id = 123 
  and b.create_date < '2013-12-01'
) y
ON 
  x.some_value = y.some_value
WHERE 
  y.some_value IS NULL

答案 1 :(得分:0)

以下是我的大脑在啤酒后发出的信息:

select distinct
    a.some_value
from
    table_a a
    join table_b b on a.id = b.a_id
where
    b.some_id = 123
    and b.create_date < '2014-01-01' 
    and b.create_date >= '2013-12-01'  
    and not exists (
        select
            a2.some_value
        from
            table_a a2
            join table_b b2 on a2.id = b2.a_id
        where
            b2.some_id = 123
            and b2.create_date < '2013-12-01'
    )

这是否优化得比左连接更快是我现在想不到的......

答案 2 :(得分:0)

我不相信左联盟是要走的路,但我相信它会是这样的:

select *
from
     (
      select *
      from a
      where a.CreateDate >= '12/1/2013'
        and a.CreateDate < '1/1/2014')December
     left join(
               select *
               from b
               where b.CreateDate < '12/1/2013')PriorMonths on December.Value = PriorMonths.Value
where PriorMonths.Value is null

“不存在”条款怎么样?

TechnetArticle

S/O question about In, Left Join, and Not Exists

select *
from a
where a.CreateDate >= '12/1/2013'
  and a.CreateDate < '1/1/2014'
  and not exists(
                 select *
                 from b
                 where b.CreateDate < '12/1/2013'
                   and b.[Value] = a.Value)