2013-01-22 63 views
0

我想知道在頁面的所有者(管理員)提出的問題中有多少條評論。SQL:連接系列

tblQuestion:(問題表)

queID 
queUserID 
queCompanyID (the owner of the page where questions are asked) 

tblReplies:(其中問題的評論被保存)

repQuestionID (queID = parent ID) 
repUserID (the user ID who made the comment) 

向tblUsers:(其中用戶存儲)

uID (user ID, autoincrement) 
uCompanyID (if this id is the same as a company id, the user is admin of that page) 

因此,我想知道公司所有者(具有uCompanyID的用戶的答覆帖子的頁數租公司ID - queCompanyID)。

我試着這樣做是爲了獲得通過網頁管理員的帖子數量,但似乎並沒有工作:

SELECT COUNT(*) tblReplies.repID 
FROM tblReplies 
JOIN 
    tblQuestions ON tblQuestions.queID = tblReplies.repQuestionID 
JOIN 
    tblUsers ON tblQuestions.queCompanyID = tblUsers.uCompanyID 
WHERE tblQuestions.queID = 68 AND tblUsers.uCompanyID = 1 

我真的希望有一個忍者在那裏誰可以幫我,我已經花了幾小時仍然沒有。

謝謝!

+0

你的模式描述似乎並不完整。例如,您的tblUsers只有一個字段,並且您沒有提及主鍵或外鍵。 – Aheho

回答

1

這應該工作(假設在tblUsersuserID

SELECT 
    count(*), 
    tblReplies.repID 
FROM 
    tblReplies, 
    tblQuestions, 
    tblUsers 
WHERE 
    tblQuestions.queID = tblReplies.repQuestionID AND 
    tblQuestions.queCompanyID = tblUsers.uCompanyID AND 
    tblUser.uID = tblReplies.repUserID AND 
    tblUsers.uCompanyID = 1 AND 
    tblQuestions.queID = 68 

GROUP BY tblReplies.repID 
+0

非常感謝您的幫助,我嘗試了此解決方案,但收到了以下內容錯誤:#1064 - 你的SQL語法有錯誤;請檢查與您的MySQL服務器版本對應的手冊,以便在第12行'tblUsers.uCompanyID = 1 AND tblQuestions.queID = 68 GROUP BY tblReplies.r'附近使用正確的語法。另外,根據您的猜測,有一個稱爲uID的用戶標識。 – David

+0

已修復,我更新了列名,但缺少AND。 – Nix

0

這應該工作。

SELECT count(*) as num_of_comments 
FROM tblQuestion a 
INNER JOIN tblReplies b 
    on a.queID = b.repQuestionID 
INNER JOIN tblUsers c 
    on b.queCompanyID = c.uCompanyID 
where a.queID = 68 
    and c.uCompanyID = 1 
+0

該解決方案給出了在父ID下添加的所有帖子。這裏是我使用的代碼:SELECT COUNT(*)AS num_of_comments FROM tblQuestions INNER JOIN tblReplies ON tblQuestions.queID = tblReplies.repQuestionID INNER JOIN向tblUsers ON tblReplies.repCompanyID = tblUsers.uCompanyID WHERE tblQuestions.queID = 68 AND tblUsers.uCompanyID = 1 – David

+0

謝謝!這就像一個魅力,我真的很感激你的幫助。 – David

0
SELECT COUNT(*) AS total 
FROM tblReplies 
WHERE repQuestionID =68 AND repUserID =1