2013-01-11 32 views
1

因此,我有一個博客列表和一個訂閱記錄列表,用於跟蹤哪些用戶訂閱了哪些博客。我想知道博客的總數至少有兩個人訂閱了他們。這裏是給定表的列表:獲取超過x個訂戶的博客數

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個或多個訂閱我想不通尚未歸還的博客。感謝您的幫助和時間。

回答

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; 
+0

完美工作。謝謝。我將重點討論HAVING子句。這是我今天學到的新東西。謝謝。 – usumoio

相關問題