I have a question for the question ;)
What would happen if the tables would look like follows? (just a small change)
type count
NULL 117
3 333
2 1
type count
NULL 807
1 3
2 32
Because in this case both tables contain records that do not match the other table, so probably joining from one direction is not enough and you need to join the tables from both directions, but then, you might have trouble using data for the 'type' from only one table...
So one solution might be something like:
select if (t1.type is null, t2.type, t1.type) as type, t1.count count1, t2.count count2
from t1
left join t2
on t1.type=t2.type or (t1.type is NULL and t2.type is NULL)
union
select if (t1.type is null, t2.type, t1.type) as type, t1.count count1, t2.count count2
from t1
right join t2
on t1.type=t2.type or (t1.type is NULL and t2.type is NULL);
In addition,
- you may also use the
coalesce()
function instead of if (.. is null, ...)
e.g. coalesce(t1.type, t2.type)
- you may still need to be careful with
union
, perhaps you want to keep duplicated records (if there is any) and use union all
http://www.sqlfiddle.com/#!2/302e69/2