user2320500
user2320500

Reputation: 169

Order results by count with MySQL

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?

Upvotes: 0

Views: 89

Answers (3)

Mi-Creativity
Mi-Creativity

Reputation: 9654

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

Upvotes: 0

Himanshu
Himanshu

Reputation: 32602

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  ║
╚══════════╝

See this SQLFiddle

Update:

You can show counts like this:

SELECT tag
      ,COUNT(tag) AS `COUNT`
  FROM tags
 GROUP BY tag
 ORDER BY COUNT(tag) DESC

See this SQLFiddle

Upvotes: 6

liyakat
liyakat

Reputation: 11853

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)

Upvotes: 0

Related Questions