Suhayb Kharabsheh Suhayb Kharabsheh - 2 months ago 6
MySQL Question

CASE condition on LEFT JOIN syntax

getting a CASE inside a set of left joins will be no more annoying after answering on this question !

however i have the following peace of query is this a correct apparoache to apply a case statement that gives a syntax error just before case statement (last parentheses) saying missing closing parentheses

from((((((`tbl_workflow_step_item`
LEFT JOIN `tbl_workflow_step_users` ON ((`tbl_workflow_step_item`.`step_id` = `tbl_workflow_step_users`.`step_id`)))
LEFT JOIN `tbl_workflow_steps` ON ((`tbl_workflow_step_item`.`step_id` = `tbl_workflow_steps`.`step_id`)))
LEFT JOIN `tbl_workflow_user_assigned` ON ((`tbl_workflow_step_users`.`user_id` = `tbl_workflow_user_assigned`.`user_id`)))
LEFT JOIN `tbl_workflow` ON ((`tbl_workflow`.`workflow_id` = `tbl_workflow_steps`.`workflow_id`)))
LEFT JOIN `tbl_report_type` ON ((`tbl_report_type`.`type_id` = `tbl_workflow_step_item`.`type`)))
case
when (`tbl_workflow`.`type` = 2)
then
left join `tbl_report_file` on ((`tbl_report_file`.`file_id`=`tbl_workflow_step_item`.`target_item_id`)))
else
LEFT JOIN `tbl_blog` ON ((`tbl_blog`.`blog_id` = `tbl_workflow_step_item`.`target_item_id`)))

Answer

No it's not good. The Case/when statement can't be used on the JOIN part. Here is what you should do :

SELECT 
 CASE
    WHEN(`tbl_workflow`.`type` = 2) 
      THEN `tbl_report_file`.YOURFIELDHERE
    ELSE
    `tbl_blog`.YOURFIELDHERE
 END AS theAliasYouWant
FROM((((((`tbl_workflow_step_item`
LEFT JOIN `tbl_workflow_step_users` ON ((`tbl_workflow_step_item`.`step_id` = `tbl_workflow_step_users`.`step_id`)))
LEFT JOIN `tbl_workflow_steps` ON ((`tbl_workflow_step_item`.`step_id` = `tbl_workflow_steps`.`step_id`)))
LEFT JOIN `tbl_workflow_user_assigned` ON ((`tbl_workflow_step_users`.`user_id` = `tbl_workflow_user_assigned`.`user_id`)))
LEFT JOIN `tbl_workflow` ON ((`tbl_workflow`.`workflow_id` = `tbl_workflow_steps`.`workflow_id`)))
LEFT JOIN `tbl_report_type` ON ((`tbl_report_type`.`type_id` = `tbl_workflow_step_item`.`type`)))
LEFT JOIN `tbl_report_file` on ((`tbl_report_file`.`file_id`=`tbl_workflow_step_item`.`target_item_id`)))
LEFT JOIN `tbl_blog` ON ((`tbl_blog`.`blog_id` = `tbl_workflow_step_item`.`target_item_id`)))