Quiero UNIR dos tablas basadas en una sola columna.
Supongamos que tengo una tabla llamada t1:
Id | Name ------------ 1 | A 2 | B 3 | CY una segunda tabla llamada t2:
Id | Name ------------ 1 | B 3 | B 5 | BQuiero UNIRLOS así:
SELECT * FROM T1 UNION SELECT * FROM T2 BASED ON IDY espero un resultado como:
Id | Name ------------ 1 | A 2 | B 3 | C 5 | BSi los ID son iguales, elija la fila de la primera tabla:
En realidad, estoy trabajando con tablas que tienen más de 20 columnas. Estas tablas son para demostración.
Una opción utiliza not exists :
select id, name from t1 union all select id, name from t2 where not exists (select 1 from t1 where t1.id = t2.id)También puede usar la agregación condicional, aunque esto es más engorroso y probablemente un poco menos eficiente:
select id, coalesce( max(case when which = 1 then name end), max(case when which = 2 then name end) ) name from ( select id, name, 1 which from t1 union all select id, name, 2 from t2 ) t group by idfrom t1 union select id, name from t2select id, name from t1 union all select id, name from t2 where not exists (select 1 from t1 where t1.id = t2.id)