I have the following 4 tables
table a: id, name, b_id, c_id
table b: id, name, d_id
table c: id, name, d_id
table d: id, name
Then I have my query, as far as I can write it:
SELECT a.name as a_name, b.name as b_name, c.name as c_name, d.name as d_name
FROM a
LEFT JOIN b ON a.b_id = b.id
LEFT JOIN c ON a.c_id = c.id
I need to add a LEFT JOIN addressing table “d” with an ON that is dynamic. It shall either be LEFT JOIN d ON b.d_id = d.id (if a.b_id != 0) or LEFT JOIN d ON c.d_id = d.id (if a.b_id == 0)
I tried to write
SELECT a.name as a_name, b.name as b_name, c.name as c_name, d.name as d_name
FROM a
LEFT JOIN b ON a.b_id = b.id
LEFT JOIN c ON a.c_id = c.id
if((if a.b_id != 0,LEFT JOIN d ON b.d_id = d.id, LEFT JOIN d ON c.d_id = d.id )
but that throws the error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'IF(a.b_id != 0, LEFT JOIN d ON b.d_id = d.id, LEFT JOIN d ON c.d_id = d.id)' at line 6"
You may try:
SELECT a.name as a_name, b.name as b_name, c.name as c_name, d.name as d_name
FROM a
LEFT JOIN b ON a.b_id = b.id
LEFT JOIN c ON a.c_id = c.id
LEFT JOIN
ON (a.b_id <> 0 AND b.d_id = d.id) OR (a.b_id = 0 AND c.d_id = d.id);
Well, you can use:
FROM a LEFT JOIN
b
ON a.b_id = b.id LEFT JOIN
c
ON a.c_id = c.id LEFT JOIN
d
ON (a.b_id <> 0 AND b.d_id = d.id) OR
(a.b_id = 0 AND c.d_id = d.id)
This doesn't take NULL values into account. If that is needed:
ON (a.b_id <> 0 AND b.d_id = d.id) OR
(COALESCE(a.b_id, 0) = 0 AND c.d_id = d.id)
In SQL, CASE is an expression that returns a value. It is not a macro where code is replaced.
Also, this answers the question that you asked here. However, this might not be the most performant way to accomplish what you want. If you also need help with performance, ask a new question. Provide sample data, desired results, and an explanation of the logic you want to implement. A DB/SQL Fiddle also helps.
You can't dynamically add join clauses like that, but you can emulate the functionality inside the join condition with some logical operators:
SELECT a.name as a_name, b.name as b_name, c.name as c_name, d.name as d_name
FROM a
LEFT JOIN b ON a.b_id = b.id
LEFT JOIN c ON a.c_id = c.id
LEFT JOIN d ON (a.b_id != 0 AND b.d_id = d.id) OR (a.b_id = 0 AND c.d_id = d.id)