我有以下两个表:joing与计数两个表值
items:
id pr1 pr2
--------------
1 11 22
...
,并与项目相关的意见表:
comments:
item_id text
------------
1 "cool"
1 "very good"
...
现在我想用item_id pr1 pr2 count(comments)
列的表。什么是最好的方式来获得它?谢谢!
我有以下两个表:joing与计数两个表值
items:
id pr1 pr2
--------------
1 11 22
...
,并与项目相关的意见表:
comments:
item_id text
------------
1 "cool"
1 "very good"
...
现在我想用item_id pr1 pr2 count(comments)
列的表。什么是最好的方式来获得它?谢谢!
只要做到这一点在一个单一的查询:
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
相同。
试试这个:
select items.id, items.pr1, items.pr2, count(*) as comment from items,comments where items.id = comments.item_id group by items.id
如果只按items.id分组,则不起作用。此外,隐式联接表示法已过时(自92开始)。 –
@ X.L.Ant在您的系统上试用它。它会给出输出。我确实运行成功。 – Yash
我做了:http://sqlfiddle.com/#!15/e548c/1不起作用。不要在MySQL上试用它,它具有特定的分组方式。请参阅http://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html –
你试过了什么? –
首先,我可以根据评论创建一个表,只有item_id,使用group by计数(评论)。然后我可以将该表与项目表一起加入。但我想知道是否有更好的方法。 – hovo
不要创建表格,只需连接两个表格和group by。 –