2011-11-14 57 views
1

設置如下工作。 但是,我要達到的目標是統計BlogComment中有多少行,其中BlogComment.BlogPostId = BlogPost.BlogPostIdSQL內部連接數和計數

任何人都有建議嗎?

SELECT * FROM BlogPost 
INNER JOIN BlogUser 
ON BlogPost.BlogUserId = BlogUser.BlogUserId 
INNER JOIN Category 
ON BlogPost.CategoryId = Category.CategoryId 
INNER JOIN BlogComment 
ON BlogPost.BlogPostId = BlogComment.BlogPostId 
Order By BlogPost.BlogPostId Desc 

回答

1

如果你想把所有的數據加上一個數(而不是僅僅計數),你可以從條款中創建一個內聯查詢做到這一點。

SELECT *, 
     COALESCE(c.count_post_id,0) as count_post_id 
FROM blogpost 
     INNER JOIN bloguser 
     ON blogpost.bloguserid = bloguser.bloguserid 
     INNER JOIN category 
     ON blogpost.categoryid = category.categoryid 
     LEFT JOIN (SELECT blogpostid, 
          COUNT(blogpostid) count_post_id 
        FROM blogcomment 
        GROUP BY blogpostid) c 
     ON c.blogpostid = blogpost.blogpostid 
ORDER BY blogpost.blogpostid DESC 

有些關係數據庫管理系統給像使用CTE或跨應用

+0

認爲這更符合我的需要。 但我收到錯誤: 列'BlogComment.BlogPostId'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 無法綁定多部分標識符「countcomments.commentcount」。 – miker

+0

@miker doh。在內聯查詢中忘記了group by子句我修復了它。 –

+0

Conrad。謝謝..但是當我運行它時得到這個。 無法綁定多部分標識符「countcomments.commentcount」。 – miker

0
SELECT COUNT(*) 
FROM blogpost a 
WHERE EXISTS (SELECT * 
       FROM blogcomment 
       WHERE blogcomment.blogpostid = a.blogpostid) 
0

嘗試:

SELECT BlogPost.*, BlogUser.*, Category.*, BlogComment.*, COUNT(BlogComment.BlogCommentId) FROM BlogPost 
INNER JOIN BlogUser 
ON BlogPost.BlogUserId = BlogUser.BlogUserId 
INNER JOIN Category 
ON BlogPost.CategoryId = Category.CategoryId 
INNER JOIN BlogComment 
ON BlogPost.BlogPostId = BlogComment.BlogPostId 
GROUP BY BlogPost.BlogPostId Order By BlogPost.BlogPostId Desc 
+0

對不起鐸,無效的SP附加選項.. – miker

+0

我編輯我的職務 - 再試一次 - 在'BlogCommentId'從'COUNT'子句表格'BlogComment'中的主鍵 - 如果不同,請用其實際名稱進行更改 –

+0

好的。我會試試看。 我想我在自己的問題上讓自己不清楚。 我只想計算來自BlogComment的行,其中BlogComment.BlogPostId匹配BlogPost.BlogPostId – miker

1

是有多少評論的每博客帖子有你想要什麼? 那麼它應該是

SELECT blogpostid, 
     COUNT(*) as TotalComments 
FROM blogpost p 
     JOIN blogcomment c 
     ON p.blogpostid = c.blogpostid 
GROUP BY blogpostid; 
+0

是的,那是正確的Mikael。我如何將你的線添加到我的sp? 還有加入AS TotalComments – miker

+0

@miker你是什麼意思?我改變了查詢來將計數命名爲totalcomments。如果您還希望在查詢結尾處添加「與彙總」的總數(對所有博客帖子) –