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

后端 未结 3 2002
轮回少年
轮回少年 2021-01-18 11:53

Trying to figure how how to replace the following, with equivalent left outer join:

select distinct(a.some_value)
from table_a a, table_b b
where a.id = b.a_         


        
相关标签:
3条回答
  • 2021-01-18 12:18

    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...

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-18 12:22
    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
    
    0 讨论(0)
提交回复
热议问题