modmoto
modmoto

Reputation: 3290

How to merge two tables on ID

I have two tables, who have the exact same columns. I want to merge table b into table a and if the dataset has the same ID, I want to use the dataset of table b.

I tried something like:

SELECT *
FROM
((SELECT 
    *
FROM
    tableA) UNION  (SELECT 
    *
FROM
    tableB)) AS temp
GROUP BY temp.ID
ORDER BY temp.ID

but that gave me a mix of both tables.

Upvotes: 1

Views: 1191

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270001

You can do this using union all along with some additional logic:

select b.*
from b
union all
select a.*
from a
where not exists (select 1 from b where b.id = a.id);

Upvotes: 2

Related Questions