Reputation: 1283
I have a very simple query , and yet I can't get it to work like I want it to.
I have 2 tables, A
and B
which are very similar and look like this :
A
:
+------+----------+---------+
| a_id | a_cnt_id | a_value |
+------+----------+---------+
| 1 | 848 | 0.5 |
| 2 | 848 | 3 |
| 3 | 848 | 4 |
| 4 | 848 | 65 |
+------+----------+---------+
B
:
+------+----------+---------+
| b_id | b_cnt_id | b_value |
+------+----------+---------+
| 1 | 849 | 36 |
| 2 | 849 | 42 |
| 3 | 849 | 8 |
+------+----------+---------+
B
has more records than A
for a given set of {a_cnt_id, b_cnt_id}
.
I would like my query to return this :
+------+------+---------+---------+
| a_id | b_id | a_value | b_value |
+------+------+---------+---------+
| 1 | 1 | 0.5 | 36 |
| 2 | 2 | 3 | 42 |
| 3 | 3 | 4 | 8 |
| 4 | NULL | 65 | NULL |
+----+--------+---------+---------+
My (not working) query, because it returns only the first 3 rows :
select distinct a.a_id, b.b_id, a.a_value, b.b_value
from b
full join a on b.b_id = a.a_id
where a.a_cnt_id = 849
and b.b_cnt_id = 848;
Upvotes: 0
Views: 50
Reputation: 320
I don't remember where I found this but here you go:
EDIT: The link of the image belongs to Visual-Representation-of-SQL-Joins. Thanks @jyparask
Upvotes: 1
Reputation: 18411
Adding a WHERE
clause will filter the results to what the where suggests. So if you have where a.a_cnt_id = 849
it will get only these rows, not the ones with the null
. Move your filters to the join:
select distinct a.a_id, b.b_id, a.a_value, b.b_value
from b
full join a on b.b_id = a.a_id
and a.a_cnt_id = 849
and b.b_cnt_id = 848;
Upvotes: 1
Reputation: 21757
Move the cnt_id
checks to the ON
clause instead to preserve the OUTER JOIN, like so:
select distinct a.a_id, b.b_id, a.a_value, b.b_value
from b
full join a on b.b_id = a.a_id
and a.a_cnt_id = 849
and b.b_cnt_id = 848;
Upvotes: 1