2011-08-19 66 views
0

我需要一個SQL查詢來獲取獨特用戶的最低分數值。我需要類似於高爾夫排行榜的東西,其中最低得分需要在最上面,但是對於給定用戶有多個條目。MySQL查詢唯一用戶和最低分數值

這是我開始用:

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

回答

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

+1同一時間,同樣的答案:) –

+0

不完全; Ria包括ORDER BY ...檢查! – AVProgrammer

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