简体   繁体   中英

Join or Union All To Combine Records?

I have 2 similar tables that contain campaign names. I know I can do an union all to combine the tables, but I was wondering if there was a way to do this using form of Join instead? I want to create a table Z with campaign names for table A plus campaign names from table B (which are not in A). Can I do this with a join or is Union ALL the only way?

SELECT * INTO TABLEZ
FROM 
  (
    SELECT Column1, Column2, Column3.... FROM TABLEA 
    UNION ALL
    SELECT Column1, Column2, Column3.... FROM TABLEB
  )Q

UNION is the easier and correct way to do that. Purely for the exercise you can do it with a JOIN but it is a lot more complex, unreadable, and the perf will be way worse...

Here is how you would do this with a full outer join :

select distinct coalesce(a.campaign, b.campaign)
from b left outer join
     a
     on a.campaign = b.campaign;

The union / union all approach is totally reasonable. I'm just offering this as a join solution that you seem to be alluding to in the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM