I have three tables : email, customer_new and customers_old. Now in email table there is a field called type that contains 0 or 1.
So if type contains 0 then I want to fetch name column from customer_new table else from customer_old table.
For this I made below mysql query :
SELECT email.*,
CASE email.`type`
WHEN 1 THEN customer_old.name
ELSE customer_new.name
END AS customer_name
LEFT JOIN
CASE email.`type`
WHEN 0 THEN customer_new ON email.customer_id = customer_new.id
ELSE customer_old ON email.customer_id = customer_old.id
END
FROM email
Now when I run this query mysql always throws error.
Can somebody solve my issue regarding join two table through CASE statement based on condition ?
Thanks in advance.
Try with below query.
SELECT email . * , IF( email.type = '1', customer_old.name, customer_new.name ) AS name
FROM email
LEFT JOIN customer_old ON ( customer_old.id = email.customer_id )
LEFT JOIN customer_new ON ( customer_new.id = email.customer_id )
select email.*,
CASE email.type
when 1 then customer_old.name
else customer_new.name
end as filteredname
from email,customer_new,customer_old
where
customer_new.id=email.id
and
customer_old.id=email.id;
You may use left join to optimize the execution.
An alternative,
SELECT * FROM email
LEFT JOIN customer_new AS customer ON email.customer_id = customer.id
WHERE email.type = 0
UNION
SELECT * FROM email
LEFT JOIN customer_old AS customer ON email.customer_id = customer.id
WHERE email.type = 1