Jump to content

[SOLVED] Most popular record in a table??


simonp

Recommended Posts

How about:

 

SELECT COUNT(*) AS `num`,`name` FROM `yourtable` GROUP BY(`name`) ORDER BY `num` DESC

 

If you do just want the most popular, rather than an ordered listing of popularity, stick a LIMIT clause on the end:

 

SELECT COUNT(*) AS `num`,`name` FROM `yourtable` GROUP BY(`name`) ORDER BY `num` DESC LIMIT 1

Link to comment
Share on other sites

Hi -thanks for that.

 

I'm struggling to get the results - I'm using:

 

$sql2 = "SELECT COUNT(*) AS 'num','victim' FROM 'victims' GROUP BY('victim') ORDER BY 'num' DESC LIMIT 1";

@$result2=mysql_query($sql2,$db);

 

How do I get the most popular name now?!

 

Cheers

 

Simon

Link to comment
Share on other sites

You don't use single quotes for starters. You use single quotes to enclose strings within you query. The character i used was the backtick (`) - which you can use to surround table names, field names etc. You don't have to do this, but i think it looks cleaner and easier to read. Anyway, Try:

 

<?php
$sql2 = "SELECT COUNT(*) AS `num`,`victim` FROM `victims` GROUP BY(`victim`) ORDER BY `num` DESC LIMIT 1";
@$result2=mysql_query($sql2,$db);
if($result2){
$row = mysql_fetch_assoc($result2);
echo 'The most popular victim is: '.$row['victim'].' who has been the victim on '.$row['num'].' occassions';
}
?>

 

Not quite sure why being the victim makes you popular, but yeah!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.