2010-04-04 51 views
2

我有以下表格:的MySQL GROUP BY三個用表

posts (post_id, content, etc) 

comments (comment_id, post_id, content, etc) 

posts_categories (post_category_id, post_id, category_id) 

與此查詢:

SELECT `p`.* 
    , COUNT(comments.comment_id) AS cmts 
    , posts_categories.* 
    , comments.* 
    FROM `posts` AS `p` 
    LEFT JOIN `posts_categories` 
    ON `p`.post_id = `posts_categories`.post_id 
    LEFT JOIN `comments` 
    ON `p`.post_id = `comments`.post_id 
GROUP BY `p`.`post_id` 

上有POST_ID = 1,總共四個三點意見。在posts_categories中有兩行,都分配給post_id = 1。我在帖子中有四行。

但是,如果我查詢上面的語句,我會在post_id = 1處得到COUNT(comments.comment_id)的結果6。這怎麼可能?我猜這個錯誤是在GROUP BY子句中的某處,但我無法弄清楚在哪裏。

有什麼建議嗎?

回答

1

作爲第一個近似嘗試

SELECT `p`.* 
    , COUNT(DISTINCT comments.comment_id) AS cmts 
    , posts_categories.* 
    , comments.* 
    FROM `posts` AS `p` 
    LEFT JOIN `posts_categories` 
    ON `p`.post_id = `posts_categories`.post_id 
    LEFT JOIN `comments` 
    ON `p`.post_id = `comments`.post_id 
GROUP BY `p`.`post_id` 

編輯:

然而,COUNT(DISTINCT場)是更昂貴的再算上(場),如果沒有必要,應避免。既然你沒有期待,我會說在你的情況下,這是沒有必要的。

您的問題來自您的連接返回3(註釋)x 2(類別)= 6行的事實。我不知道你使用什麼結果,但也許你應該重新考慮你的查詢。

0

我的猜測是你有多個類別參與!

是否

SELECT P.post_id 
    , PC.post_category_id 
    , COUNT(C.comment_id) AS cmts 
    FROM `posts` AS P 
    LEFT JOIN `posts_categories` as PC 
    ON `p`.post_id = `posts_categories`.post_id 
    LEFT JOIN `comments` as C 
    ON P.post_id = C.post_id 
GROUP BY P.post_id, PC.post_category_id 

給你一個 '可以理解' 的結果?

BTW你應該有BY子句中的組中的所有字段不聚集......

+0

在mysql中,並不需要列出GROUP BY中的所有字段,但是這會導致上述問題,因此需要計數 – Unreason 2010-04-04 17:58:22

+0

post_category_id怎麼辦?你是否嘗試過查詢。如果你不明白我的意思,請看@Adam Bernier的回答。 – lexu 2010-04-04 18:05:28

+0

不適用於我,我省略了GROUP_CONCAT以簡化查詢。無論如何,謝謝 – Psaniko 2010-04-04 18:30:40

0

你得到六(6)的意見,因爲你的結果集看起來是這樣的:
(注意兩個組每三排;爲每個崗位類別,簡稱PCAT *)

 
post_id cmts post_cat comments 
1  6  pcat1  comment text... 
1  6  pcat1  comment text... 
1  6  pcat1  comment text... 
1  6  pcat2  comment text... 
1  6  pcat2  comment text... 
1  6  pcat2  comment text... 

你可以做這樣的事情,而不是:

SELECT `p`.post_id, 
     COUNT(comments.comment_id) AS cmts, 
     COUNT(posts_categories.) AS categories 
    FROM `posts` AS `p` 
     LEFT JOIN `posts_categories` 
     ON `p`.post_id = `posts_categories`.post_id 
     LEFT JOIN `comments` 
     ON `p`.post_id = `comments`.post_id 
GROUP BY `p`.`post_id` 
+0

對不起,但我總是得到6評論這是definetely錯誤。我可能沒有足夠的解釋我想得到的,謝謝。 – Psaniko 2010-04-04 18:26:36