Thursday, 30 August 2018

merge two tables according to the primary key

I have two table with some entries same, eg table A:

ID         value        type
1          1            2
2          3            2
3          3            2

table B:
ID        value        type
2          3            1
3          3            1
4          1            1

I want to merge them so that resulting table looks like
table C:
ID        value        type
2          3            2
3          3            2
4          1            1

ie , remove the rows that are not in table A, display rows that have duplicate in table A with table A's type and also display those rows that are not in Table A.
Till now i have done UNION command to remove duplicate
 select * from table A union select * from table B

but how to get type from table A? can this be done or i have to separately update them.

You can do it with a LEFT JOIN :
SELECT b.id,b.value,
       COALESCE(a.type,b.type) as type
FROM TableB b
LEFT JOIN TableA a
 ON(a.id = b.id)

0 comments:

Post a Comment