I have a table that stores a list of tags. I would like to be able to write a script that displays the tags a user uses the most. But, I am having trouble with writing the MySQL query to do so.
Table Structure:
tag_id | user_id | tag
--------------------------------
1 | 1 | hiking
2 | 1 | fishing
3 | 1 | hiking
4 | 1 | swimming
5 | 1 | hiking
6 | 1 | swimming
What I have so far just outputs all of the tags:
$query= "SELECT tag FROM tags WHERE user_id='1'";
I would like the results to look like this:
hiking
swimming
fishing
Can I use an order by "Count" or something to achieve this?
You need to order by COUNT
Try this:
SELECT tag
FROM tags
GROUP BY tag
ORDER BY COUNT(tag) DESC
Output:
╔══════════╗
║ TAG ║
╠══════════╣
║ hiking ║
║ swimming ║
║ fishing ║
╚══════════╝
You can show counts like this:
SELECT tag
,COUNT(tag) AS `COUNT`
FROM tags
GROUP BY tag
ORDER BY COUNT(tag) DESC
yes as per your latest comment see my below solution to work out.
SELECT tag FROM tags
GROUP BY tag
ORDER BY tag ASC,COUNT(tag)
just like what hims suggested just add , count(*) to the tag column name
SELECT tag, count(*) FROM tags GROUP BY tag ORDER BY COUNT(tag) DESC
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.