2010-04-10 46 views
9

我有三個表如何JOIN從一個表的計數,然後實現與另一種COUNT JOIN

ID Name 
1 'Something' 
2 'Something else' 
3 'One more' 

評論

ID PostId ProfileID Comment 
1 1  1   'Hi my name is' 
2 2  2   'I like cakes' 
3 3  3   'I hate cakes' 

檔案

ID Approved 
1 1   
2 0   
3 1   

我想數t他評論的評論的個人資料被批准

我可以從帖子中選擇數據,然後從評論加入計數罰款。但是這個數字應該取決於配置文件是否被批准。

我期待的結果是

CommentCount

PostId Count 
1  1 
2  0 
3  1 
+0

是'Profile'表1-1與'Comment'一個? – 2010-04-10 10:36:57

+1

不,一個配置文件可以做出許多評論。 – 2010-04-10 10:44:36

回答

11

你可以使用一個嵌套的選擇是這樣的:

SELECT Post.Id, temp.Count 
FROM Post 
LEFT JOIN 
(SELECT Post.Id, COUNT(Comment.ID) AS Count 
FROM Post 
LEFT JOIN Comment ON Comment.PostId = Post.ID 
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID 
WHERE Profile.Approved = 1 
GROUP BY Post.Id) 
temp ON temp.Id = Post.ID 

這將使你空在那裏沒有任何職位,而不是沒有記錄:

1 1 
2 null 
3 1 

只是爲了改善這一點,你可以使用一個if來擺脫空值

SELECT Post.Id, if(temp.Count >= 1,temp.Count,0) as newCount 
FROM Post 
LEFT JOIN 
(SELECT Post.Id, COUNT(Comment.ID) AS Count 
FROM Post 
LEFT JOIN Comment ON Comment.PostId = Post.ID 
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID 
WHERE Profile.Approved = 1 
GROUP BY Post.Id) temp ON temp.Id = Post.ID 

哪給你你最初想要的:

1 1 
2 0 
3 1 

注:最有可能是一個更優雅的解決方案,雖然!!!!

+0

好的工作。謝謝! – 2010-04-11 10:48:57

1
SELECT Post.Id, COUNT(Comment.ID) AS Count 
FROM Post 
LEFT JOIN Comment ON Comment.PostId = Post.ID 
LEFT JOIN Profile ON Profile.ID = Comment.ProfileID 
WHERE Profile.Approved = 1 
GROUP BY Post.Id 

也許你沒有粘貼的例子的目的,但你可能會評估到反規範化的Profile表與Comment一起,移動Approved列。

+0

這是一個好主意!雖然意味着需要更多的編碼,以確保當配置文件被批准和暫停時,表格保持最新狀態。 另外,如何讓表名在代碼中以代碼的形式顯示? – 2010-04-10 10:43:55

+0

使用你的〜鍵,'盧克' – jonny 2010-04-10 10:50:44

+0

這給了我正確的計數,但只有'帖子'有'評論'。即使他們沒有任何評論,我也需要返回所有'Posts'。我在開始時並沒有明確表示道歉。 – 2010-04-10 11:23:57

4

從COUNT函數的定義:

COUNT函數將只計算那些 記錄,其中在 括號中的字段不爲空。

這意味着,簡單的外連接像這樣的工作:

SELECT Post.ID, COUNT(Comment.ID) 
    FROM Post LEFT JOIN Comment ON (Post.ID = Comment.PostId) 
      LEFT JOIN Profile ON (Profile.ID = Comment.ProfileID AND 
            Profile.Approved = 1) 
GROUP BY Post.ID 
+0

這也不起作用,它只返回兩行。即使「COUNT」爲空,我也需要返回所有行。 – 2010-04-11 10:47:48

+0

對不起,當然它不 - 看看我如何移動Profile.Approved條件來修復它... – topchef 2010-04-11 17:55:36

+2

+1這應該是答案。 – 2012-03-05 23:56:53