advanced joining question

Copper Contributor

Hi

I'm familiar in joining tables, but I have a real problem on this one:

 

4 tables. All have one identity column which can be used to join the tables. All 4 tables have or doesn't have a specific ID. I try to join the tables by this ID. A row should be returned regardless if the other tables contain the ID or not. So if only table A contains the ID, it should return return the row. Same if only table B contains a specific ID. If both contains the ID it should combine them to one row. Same for all other combinations of the 4 tables.

 

I have also tried FULL OUTER JOIN only 3 tables, but the result is wrong (http://sqlfiddle.com/#!18/0a1e5/1). Another solution I tried is to join table A-B and A-C apart and full outer join both subquerys and UNION to rows where ID only exist in table A, B or C.


Have someone a solution for this problem?


Kind regards
sqljimmy11

 

 

 

 

 

2 Replies

Good day @sqljimmy11,

 

Your question is totally not clear as you claim that "the result is wrong" but in your demo the result are exactly as expected which mean that your expectation is wrong.

 

If you can explain what is your expectation then maybe we will be able to explain why it is wrong and the result is correct.

 

Maybe the following tutorial can help you a bit more:
https://www.w3resource.com/sql/joins/perform-a-full-outer-join.php

 

Let me go over your result, but first!

(1) We must use ORDER BY for the sake of the discussion since the returned order is not guarantee without ORDER BY and therefore we will have difficult to describe the result.

(2)I will add in the result ROW_NUMBER in order to get the number of the row in our order (for the sake of the discussion.

So, the query I uses is yours+ORDER BY

 

select RN = ROW_NUMBER() OVER (ORDER BY a.id desc, b.id desc, c.id desc, bc.id desc), *
from kombinatorik_3a as a
full outer join kombinatorik_3b as b on a.id = b.id
full outer join kombinatorik_3c as c on a.id = c.id
full outer join kombinatorik_3c as bc on b.id = bc.id
ORDER BY a.id desc, b.id desc, c.id desc, bc.id desc

 

* You should use the name of the columns explocotly and not like you did! I use the same format only for the sake of using your query with little changes as can be

 

A row should be returned regardless if the other tables contain the ID or not. So if only table A contains the ID, it should return return the row.

True, and this is what you get in the result on rows 1-4, all the ID from the first table are there

image.png

Same if only table B contains a specific ID.

True, and all the ID from table B are in rows 1,3,5,6

and all the ID from table C are in rows 1,2,7.8

Here is the link to the demo:

http://sqlfiddle.com/#!18/0a1e5/24/0