简体   繁体   English

SQL计数不同吗?

[英]SQL Count Distinct?

I have a table that is laid out as below: 我有一个表,其布局如下:

id - tag_id - post_id
1  -    1   -  3
2  -    1   -  6
3  -    1   -  2
4  -    2   -  3
5  -    2   -  9
6  -    1   -  7

I would like to write an mySQL statement that finds out how many times a tag is referenced. 我想写一条mySQL语句来找出标记被引用了多少次。

I would then use PHP to format the results. 然后,我将使用PHP格式化结果。 tag # was referenced # times and they would be sorted in order of # times . tag # was referenced # times ,它们将按# times顺序进行排序。

My ability with MySQL is limited to very basic SELECT, INSERT, UPDATE and DELETE statements, so I'm not sure of the way to go about this. 我使用MySQL的能力仅限于非常基本的SELECT,INSERT,UPDATE和DELETE语句,因此我不确定该怎么做。 Can you help? 你能帮我吗?

select tag_id, count(*)
from mytable
group by tag_id
order by count(*) desc

This will order your results by count(*) in descending order, meaning the tags with most posts will appear on top rows. 这将按照count(*)的降序对结果进行排序,这意味着帖子数量最多的标签将显示在顶部。

SELECT tag_id, COUNT(*) FROM table GROUP BY tag_id将为您提供每个标签id的计数

To get the tags and the number of posts each tag has, sorted in descending order, you could use the following query : 要获取标签以及每个标签的帖子数(以降序排列),可以使用以下查询:

select tag_id, count(*) as num
from your_table
group by tag_id
order by count(*) desc

(Of course, if you want the same data, but sorted in ascending order, just remove the desc in the order by clause) (当然,如果您想要相同的数据,但按升序排序,只需在order by子句中删除desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM