How to replace a complex SQL MINUS query with LEFT OUTER JOIN equivalent

拥有回忆 提交于 2019-12-01 19:14:27
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

Here's what my brain puts out after a beer:

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'
    )

Whether this'll optimize to faster than a left join or not is something I can't think of right now...

agileMike

I'm not convinced a left join is the way to go but I believe it would look like this:

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

How about a "not exists" clause?

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!