[英]SQL query for getting count and distinct
I have the following table called user_pin_tags
with the following data that I need to query and show distinct tags and a count of each: 我有一个名为
user_pin_tags
的下表, user_pin_tags
包含以下数据,我需要查询这些数据并显示不同的标记以及每个标记的计数:
| user_id | pin_id | tag_id |
+---------+--------+--------+
1 | 34 | 7
2 | 34 | 7
3 | 34 | 15
4 | 34 | 16
5 | 34 | 16
6 | 34 | 16
Right now I am using the following query to get the distinct tag_ids 现在,我正在使用以下查询来获取不同的tag_id
SELECT DISTINCT tag_id
FROM user_pin_tags
WHERE pin_id = 34
which gives the result of: 结果如下:
| tag_id |
+--------+
7
15
16
I need to modify this query to give the distinct tag_ids as well as the count within that pin_id, so I want to generate this result set: 我需要修改此查询以提供不同的tag_id以及该pin_id中的计数,因此我想生成此结果集:
| tag_id | count |
+--------+-------+
7 | 2
15 | 1
16 | 3
How can I modify this query to achieve this? 如何修改此查询以实现此目的?
Use COUNT(*)
and GROUP BY
: 使用
COUNT(*)
和GROUP BY
:
SELECT tag_id, COUNT(*) AS total
FROM user_pin_tags
WHERE pin_id = 34
GROUP BY tag_id
SELECT
DISTINCT(tag_id)
,count(pin_id)
FROM user_pin_tags
WHERE pin_id = 34
GROUP BY tag_id
Group By should do it ... i think. Group By应该这样做...我认为。
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
You can group by the tag_id: 您可以按tag_id分组:
SELECT tag_id, COUNT(pin_id)
FROM user_pin_tags
WHERE pin_id = 34
GROUP BY tag_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.