samedi 4 juillet 2020

Selecting a value from a table with a dynamically where statement

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"

Aucun commentaire:

Enregistrer un commentaire