MySQL查询唯一用户和最低分数值

时间:2011-08-19 17:28:37

标签: php mysql

我需要一个SQL查询来获取唯一身份用户的最低得分值。我需要类似于高尔夫排行榜的东西,其中得分最低,但给定用户有多个条目。

这就是我的开始:

<?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));
?>

这是以独特的用户名返回,但不是他们的最低分,它只是抓住它找到的第一个分数。如何让它返回最低分?


谢谢RiaD!这最终对我有用:

SELECT `username`, `id`, MIN(`score`) as mn, `type`, `created` FROM `scores` WHERE `username` != "" GROUP BY `username` ORDER BY `mn` ASC

2 个答案:

答案 0 :(得分:4)

select username, MIN(score) as minscore from  scores where ... GROUP BY username 

答案 1 :(得分:3)

SELECT username, MIN(score) as mn FROM scores GROUP BY username ORDER BY mn