If I have two tables
CREATE TABLE R
(
a int,
b int
);
CREATE TABLE S
(
b int,
c int,
d int
);
INSERT INTO R
VALUES (3,1),(2,3),(2,0),(3,3),(1,1);
INSERT INTO S
VALUES (2,2,3),(3,0,0),(1,3,3),(2,2,0);
Then I do R outer join S
. I'm trying to figure out the result. If I try to use sql code, I would do:
SELECT r.a,r.b,s.c,s.d
FROM R r
LEFT JOIN S s ON r.b=s.b
UNION
SELECT r.a,r.b,s.c,s.d
FROM R r
RIGHT JOIN S s ON r.b=s.b
The result of that query is:
A B C D
3 1 3 3
2 3 0 0
2 0 - -
3 3 0 0
1 1 3 3
- - 2 3
- - 2 0
If I try to solve it by hand:
The 3 1
matches with 1 3 3
The 2 3
matches with 3 0 0
The 2 0
matches with - - -
The 3 3
matches with 3 0 0
The 1 1
matches with 1 3 3
This makes the first 5 rows above in that result. The two remaining rows come from the right join. But what I don't understand is why the right join produces
- - 2 3
- - 2 0
Because on the left join the 2 0
didn't match with anything, yet the b
column was preserved and the 0 was there.
But on the right join, the 2 2 3
and 2 2 0
didn't match with anything but the b column turned into a null. Shouldn't the b column be preserved here like in the left join?
Can anyone explain whats going on here?
Thanks.