I need a SQL query for getting the lowest value of score for unique users. I need something similar to a golf leaderboard, where the lowest score needs to be on top, but there are multiple entries for a given user.
This is what I’m starting with:
<?php
$order_by['score'] = 'asc';
$sql = 'SELECT DISTINCT(`username`), `id`, `score`, `type`, `created` FROM `scores` WHERE `username` != "" ';
$sql .= 'GROUP BY `username` ';
if(is_array($order_by)){
$sql .= 'ORDER BY ';
foreach($order_by as $field => $ascDesc){
$order_by_array[] = '`'.$field.'`' . ' ' . strtoupper($ascDesc);
}
$sql .= implode(', ', $order_by_array);
}
$results = mysql_query($sql) or die(mysql_error($con));
?>
This is coming back with unique usernames, but not their lowest score, it just grabs the first score it finds. How can I get it to return the lowest score?
Thanks RiaD! This is ultimately what worked for me:
SELECT `username`, `id`, MIN(`score`) as mn, `type`, `created` FROM `scores` WHERE `username` != "" GROUP BY `username` ORDER BY `mn` ASC
1 Answer