1. Welcome! Please take a few seconds to create your free account to post threads, make some friends, remove a few ads while surfing and much more. ClutchFans has been bringing fans together to talk Houston Sports since 1996. Join us!

Any SQL Nerds available?

Discussion in 'BBS Hangout' started by aeroman10, Aug 5, 2013.

Tags:
  1. Depressio

    Depressio Member

    Joined:
    Mar 3, 2009
    Messages:
    6,416
    Likes Received:
    366
    Someone has probably suggested this, but:

    select name, col1, col2 from T1 where name not in (select name from T2)
    union
    select name, col1, col2 from T2


    The idea being: get everything from T1 that isn't in T2, and union that with everything in T2 (since they get priority). Depends if name is the primary key, of course. If there are multiple key columns, you an always do where (key1, key2, key3) not in (select key1, key2, key3 from T2). Efficacy may depend on SQL variant.
     
  2. heypartner

    heypartner Member

    Joined:
    Oct 27, 1999
    Messages:
    63,510
    Likes Received:
    59,001
    This is the most concise. Plus, I'm pretty sure this will work for every flavor of SQL out there.


    Code:
    select ISNULL(t1.name, t2.name) name, ISNULL(t2.value,t1.value) value
    from
    t1 full outer join t2 on t1.name = t2.name
    Below is a good learning example. It shows how the JOINs actually work. (I'm pretty sure this is what SQL server will turn the above into in its execution plan.) But I don't think I've ever used UNION in my life. lols

    Code:
    select ISNULL(t1.name, t2.name) name, ISNULL(t1.value,t2.value) value
    from t1 left join t2 on t1.name = t2.name
    where t2.name IS NULL
    union
    select ISNULL(t2.name, t1.name) name, ISNULL(t2.value,t1.value) value
    from t1 right join t2 on t1.name = t2.name
    where t1.name IS NULL OR t1.name = t2.name
    
     
    #22 heypartner, Aug 9, 2013
    Last edited: Aug 9, 2013
  3. heypartner

    heypartner Member

    Joined:
    Oct 27, 1999
    Messages:
    63,510
    Likes Received:
    59,001
    I'm pretty sure this does not work when T2 has a unique record that T1 does not. Plus, it's Oracle only
     

Share This Page