I am facing an issue with a conditional join.
This is my query :
SELECT table_b.name
FROM table_a
LEFT JOIN table_b
ON table_a.id = table_b.a_id
The description of my table_b :
id, a_id, ref_z, name
----------------------
1 | 0 | 1 | James
2 | 0 | 2 | John
3 | 2 | 2 | John. S
4 | 0 | 3 | Martin
5 | 6 | 3 | Martin. M
6 | 2 | 3 | Martin. M. Mr
Let’s say I have a parameter @a_id.
I would like to join table_a and table_b ON table_a.id = @a_id if it exists else on 0.
So the output of the previous query will be (with @a_id = 2) :
James
John. S
Martin. M. Mr
Anyone has an idea, a blog post, a man page or anything else that can lead me to a correct query ?
Thank you,
your join can be shorten into
using (a_id)since both columns have the same name and there is no ambiguity.on / usingshould not be confused for your predicate clause (where)