I’ve got a table called hg_liveitems that holds items currently on a website. The ‘type’ field can be fruit, veg, or trees. There are separate tables for fruit, trees and veg all with the same fields. Basically I need a query that chooses the correct name field as well as the correct table to join with. At the minute I have this:
SELECT `hg_liveitems`.`id`, `hg_liveitems`.`price`, `hg_liveitems`.`grabs`, `hg_liveitems`.`quantity`, `hg_liveitems`.`created`
CASE `hg_liveitems`.`type`
WHEN '1' THEN `hg_fruit`.`name`
WHEN '2' THEN `hg_trees`.`name`
WHEN '3' THEN `hg_veg`.`name`
END AS `name`
FROM `hg_liveitems`
INNER JOIN
CASE `hg_liveitems`.`type`
WHEN '1' THEN `hg_fruit` ON `hg_liveitems`.`produce_id` = `hg_fruit`.`id`
WHEN '2' THEN `hg_trees` ON `hg_liveitems`.`produce_id` = `hg_trees`.`id`
WHEN '3' THEN `hg_veg` ON `hg_liveitems`.`produce_id` = `hg_veg`.`id`
END
WHERE `hg_liveitems`.`grower_id` = '2'
AND `hg_liveitems`.`status` < '2'
but I’m just getting errors, and I don’t know enough about the CASE statement to know what’s up.
You cannot do a conditional inner join like that – it’s a syntax error. Consider re-writing as three outer joins and a where clause to limit the results.