I need to full join two tables with multiple keys
As an example, I have two tables, one looks like:
id1 | foreignerkey | name | value
1 5 name1 1
2 6 name2 2
3 7 name4 3
as t01; the other looks like:
id2 | foreignerkey | name | value
1 5 name1 1
2 7 name2 2
3 8 name2 3
as t02.
I need “select t01.* , to2.* from t01 full join t02 on t01.name = t02.name“,
but I need also “select t01.* , t02.* from t01 join t02 where t01.foreignerkey = t02.foreignerkey“, the result I need is like this:
id1 | foreignerkey | name | value | id2 | foreignerkey | name | value
1 5 name1 1 1 5 name1 1
2 6 name2 2 null null null null
3 7 name4 3 null null null null
null null null null 2 7 name2 2
null null null null 3 8 name2 3
The problem is, as you can see, at first, I put my query string like this,
“select t01.* , t02.* from t01 full join t02 on t01.name = t02.name where“, but then when
t01.foreignerkey = t02.foreignerkeyt01.name = "name4" (which is not in t02), it won’t show up in the results.
So, my final query string:
select a.* from
(select t01.id1, t01.foreignerkey as foreignerkey1, t01.name, t01.value,
t02.id2, t02.foreignerkey as foreignerkey2, t02.name, t02.value
from t01
full join t02
on t01.name = t02.name) a
where a.foreignerkey1 = a.foreignerkey2
or a.foreignerkey1 is null
or a.foreignerkey2 is null
It costs too much to get the results, is there a better solution?
I can’t verify that this is faster as your original SQL doesn’t work on the version of Oracle I’m using but you could try this:
Or you can use an outer join as @kedar kamthe has sugested:
But you still need the second query to return the results from t02