2014-12-22 38 views
0

我有以下兩個表:joing與計數兩個表值

items: 
id pr1 pr2 
-------------- 
1  11 22 
... 

,並與項目相關的意見表:

comments: 
item_id text 
------------ 
1 "cool" 
1 "very good" 
... 

現在我想用item_id pr1 pr2 count(comments)列的表。什麼是最好的方式來獲得它?謝謝!

+0

你試過了什麼? –

+0

首先,我可以根據評論創建一個表,只有item_id,使用group by計數(評論)。然後我可以將該表與項目表一起加入。但我想知道是否有更好的方法。 – hovo

+0

不要創建表格,只需連接兩個表格和group by。 –

回答

2

只要做到這一點在一個單一的查詢:

SELECT items.id, 
     items.pr1, 
     items.pr2, 
     COUNT(*) AS comment_count 
FROM items 
     INNER JOIN comments 
       ON items.id = comments.item_id 
GROUP BY items.id, 
      items.pr1, 
      items.pr2 

編輯

如果所有未分組列functionnally依賴於分組之一,看來,你可以只此列組(如佳日一樣):

SELECT items.id, 
     items.pr1, 
     items.pr2, 
     COUNT(*) AS comment_count 
FROM items 
     INNER JOIN comments 
       ON items.id = comments.item_id 
GROUP BY items.id 

請參閱:

編輯2

關於添加第二個表(讓我們tags):

你不能只是去COUNT荷蘭國際集團上*。嘗試:

SELECT items.id, 
     items.pr1, 
     items.pr2, 
     COUNT(DISTINCT comments.*) AS comment_count, 
     COUNT(DISTINCT tags.*) AS tags_count 
FROM items 
     INNER JOIN comments 
       ON items.id = comments.item_id 
     INNER JOIN tags 
       ON items.id = tags.item_id 
GROUP BY items.id, 
     items.pr1, 
     items.pr2 

通過comments使用DISTINCT,你會COUNT每行只有一次,並與tags相同。

+0

你的代碼正常工作。我的代碼已被棄用。 – Yash

+0

X.L.Ant ..........很好。我很欣賞這一點。 – Yash

+0

如果有另一個表如評論,說標籤,並且在最終結果中我想要顯示評論數和標籤數? – hovo

3

試試這個:

select items.id, items.pr1, items.pr2, count(*) as comment from items,comments where items.id = comments.item_id group by items.id 
+0

如果只按items.id分組,則不起作用。此外,隱式聯接表示法已過時(自92開始)。 –

+0

@ X.L.Ant在您的系統上試用它。它會給出輸出。我確實運行成功。 – Yash

+0

我做了:http://sqlfiddle.com/#!15/e548c/1不起作用。不要在MySQL上試用它,它具有特定的分組方式。請參閱http://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html –