I have 3 InnoDB tables: emails, websites and subscriptions.
emails table has id and email columns.
websites table has id and address columns.
subscriptions table has id, email_id and website_id columns.
What I’m tring to do is supply an email and return a table with columns address and subscribed. The former is a list of all the addresses in the websites table and the latter gets value 1 if the supplied email address has an occurence in the subscriptions table with website_id set to that website, or 0 otherwise. But I’m willing to retain all the websites even if the user is not found.
The point I’m stuck is where I should change the value of the virtual column subscribed from 0 to 1 when that email has that record.
Here’s my query so far. Does anybody know how to do this?
SELECT `address`, "0" AS `subscribed`
/* 0 becomes 1 for the websites email has subscribed to */
FROM `websites` a
LEFT JOIN (
SELECT s.`website_id` FROM `subscriptions` s
RIGHT JOIN (
SELECT `id` AS `email_id` FROM `emails`
WHERE `email`='someone@mail.com' LIMIT 1) e
ON s.`email_id`=e.`email_id`) l
ON l.`website_id`=a.`id`
And here are the example outputs for the desired values for the subscribed column:
- If email is not found in the
emailstable all the rows get value 0 - If email is found in the
emailstable…- if it is not found in
subscriptionstable all the rows get value 0 - if it is found in
subscriptionstable, the appropriate address rows get value 1
- if it is not found in
Let me know if I couldn’t wxplain it well. Does anytbody know what I should alter in my query?
Thanks in advance.
You could also come up with the subscribed value this way, which is a bit more concise but also somewhat less obvious.