I have two tables
- Magazines with fields id, name;
- Subscriptions with fields subscriber_id and magazine_id, which are foreign keys from Magazines and another table of subscribers.
I would like to extend the Magazines table to have:
- a third column listing its total number of subscribers and
- a fourth column subscribed which has a boolean value which is true iff a record exists in Subscriptions with my subscriber_id (we can say I am subscriber_id=1).
Is there a canonical way to solve these problems? If not how can I do this efficiently?
To get the subscribers column, the simplest thing I thought of doesn't list magazines with no subscribers. (I did read here but couldn't see how it's related)
SELECT magazine_id, COUNT(*)
FROM subscriptions GROUP BY magazine_id
ORDER BY magazine_id ASC;
So instead I did something a bit hacky and probably inefficient:
SELECT
magazines.id,
CASE WHEN NOT EXISTS(
SELECT * FROM subscriptions WHERE magazines.id=magazine_id
) THEN 0
ELSE COUNT(*) END AS subscribers
FROM
magazines
LEFT JOIN
subscriptions
ON
magazines.id = subscriptions.magazine_id
GROUP BY
magazines.id
ORDER BY
magazines.id ASC;
For the boolean fourth column, I got a solution by left joining the previous result with subscriptions again, and doing case when is null for the value of the subscriber_id.
I am using PostgreSQL. I'm not a student but I'd like to learn how to solve this problem, magazines/subscribers is just an example. I know only basics of SQL.