所以我有一个博客列表和一份订阅记录列表,用于跟踪哪些用户订阅了哪些博客。我想知道博客的总数至少有两个人订阅了它们。以下是给定表的列表:
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,
);
我尝试了一些只使用一个查询来获取原始数字的东西,因为我不知道在PHP中处理什么来解决这个问题。以下是我尝试过的一些尝试:
#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;
然而,限制该查询仅返回具有2个或更多订阅的博客我还想不通。感谢您的帮助和时间。
答案 0 :(得分:4)
使用HAVING子句过滤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;