简体   繁体   中英

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.

I would then use PHP to format the results. tag # was referenced # times and they would be sorted in order of # 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. 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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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