Question

So I have a list of blogs and a list of subscription records that track which users are subscribed to which blogs. I want to know the total number of the blogs have at least two people subscribed to them. Here is a list of the given tables:

CREATE TABLE IF NOT EXISTS `blogs` (
    `id` int(11) NOT NULL,
    `name` varchar(255),
    `user_id` int(11)
);

CREATE TABLE IF NOT EXISTS `subscribers` (
   `user_id` int(11) NOT NULL,
   `blog_id` int(11) NOT NULL,
);

I have tried a few things to get the raw number using only one query, as I don't what to do processing in PHP to solve this. Here are a few of my tries that have not worked:

#This was my attempt to just count the results of a subquery on the subscribers table (FAILED)
SELECT COUNT(*) FROM (SELECT COUNT(*) as subs_count FROM `subscribes` WHERE subs_count > 1) AS dummy_table WHERE 1;

#This was my attempt to produce a count of the number of subscribers and count that (FAILED)
SELECT COUNT(*) FROM `subscribes` WHERE count(*) >= 2 GROUP BY blog_id;

#I'm sure of how to get the number of subscribers to each blog irregardless of subscription count, that query looks as followed:
SELECT id, title, COUNT(*) as subs_count FROM `blogs`, `subscribers` WHERE `blogs`.`id` = `subscribers`.`blog_id` GROUP BY `blog_id` ORDER BY subs_count DESC;

However restricting that query to only return the blogs with 2 or more subscribes I cannot figure out yet. Thank you for your help and time all.

Was it helpful?

Solution

Use a HAVING clause to filter your GROUP BY.

SELECT id, title, COUNT(*) as subs_count  
FROM `blogs`, `subscribers`  
WHERE `blogs`.`id` = `subscribers`.`blog_id`
GROUP BY `blog_id`
HAVING COUNT(*) >= 2
ORDER BY subs_count DESC;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top