PDA

View Full Version : Finding most frequent result in sql query


Railsplitter44
04-25-2008, 03:22 AM
Hello,

I have a mysql table and I would like to display some of its info. One of the columns contains a lot of duplicate values and I would like to create a query that will display the 5 most frequent of these values and how many times it appears.

I am fairly new to php/mysql and I have searched the internet and my reference books for a solution and have been unsuccessful. I would appreciate any assistance on this if possible.

Thank you very much

Dfraz
04-25-2008, 07:23 AM
Yoda.

So lets see, If you're saying you want it to sort by whatever and limit it to how many rows?

EXAMPLE:

$result = mysql_query("SELECT * FROM example order by id DESC LIMIT 5") or die("mysql_error()); ?>

chaosprime
04-25-2008, 02:59 PM
SELECT `dupedval`, COUNT(*) as `c`
FROM `yourtable`
GROUP BY `dupedval`
ORDER BY `c` DESC
LIMIT 5

Railsplitter44
04-25-2008, 06:42 PM
Chaos, I tried your example and it worked. Thank you for your help

chaosprime
04-25-2008, 08:26 PM
You're welcome. :)