As I am now aware, CASE can be used only in WHERE context. Though, I need to use different table depending on column value. What I’ve tried looks like this:
SELECT
`ft1`.`task`,
COUNT(`ft1`.`id`) `count`
FROM
`feed_tasks` `ft1`
CASE
`ft1`.`type`
WHEN
1
THEN
(INNER JOIN `pages` `p1` ON `p1`.`id` = `ft1`.`reference_id`)
WHEN
2
THEN
(INNER JOIN `urls` `u1` ON `u1`.`id` = `ft1`.`reference_id`)
WHERE
`ft1`.`account_id` IS NOT NULL AND
`a1`.`user_id` = {$db->quote($user['id'])}
Now that I know this is invalid syntax, what’s the closest alternative?
It probably needs tweaking to return the correct results but I hope you get the idea:
Edit:
A little note about
CASE...END. Your original code does not run because, unlike PHP or JavaScript, the SQLCASEis not a flow control structure that allows to choose which part of the code will run. Instead, it returns an expression. So you can do this:… but not this: