2010-08-23 3 views
2

좋아, 나는 두 MYSQL 테이블을 가지고있다. 이제 총 점수가 높은 PHP 파일을 만들고 싶지만 PHP에 대한 지식이 거의없고 MYSQL에 대한 지식이 없기 때문에 시작할 방법을 모르겠다. 총 높은 점수는 총 런타임별로 정렬됩니다.SQL의 최고 기록

예 : 사용자의 경우 사용자 # 1 (코디) & 사용자 # 2 (조)가 있습니다.

id, userID, runTime, monstersKilled, profit, tasks, xpGain, lastupdate 
12, 1, 27, 14, 6200, 0, 5050, 1282325410 
19, 1, 18, 1, 277, 1, 168, 1278897756 
1968, 2, 195, 433, 111345, 4, 73606, 1280993244 

인쇄 아웃의 라인을 따라해야한다 : 이제 세션에서 나는 3 개 세션을 가질

Place, username, Total Run Time, Total Monsters Killed, Total profit, Total tasks, Total Exp Gain 
1. Joe, 195, 433,11345,4,73606 
2. Cody, 55, 15, 1, 5218 

답변

5

사용 :

SELECT u.user, 
     SUM(s.runtime) AS total_run_time, 
     SUM(s.monsterskilled) AS total_monsters_killed, 
     SUM(s.profit) AS total_profit, 
     SUM(s.tasks) AS total_tasks, 
     SUM(s.xpgain) AS total_xp_gained 
    FROM USERS u 
    JOIN SESSION s ON s.userid = u.userid 
GROUP BY u.user 
ORDER BY total_run_time DESC 
+0

좋은 답변이지만, MySQL을 많이 사용하지 않으므로 행 범위를 지원하는지 잘 모르겠지만 SELECT TOP n 또는 SELECT 범위를 사용하려면이 쿼리가 쉽게 될 수 있습니다. 많은 사용자에게 속도가 느립니다. –

+0

@Tom Gullen : MySQL의'LIMIT' 문법은 SQL Server의'TOP' 문법과 동일합니다. 실제로'offset' 매개 변수를 사용할 때보 다 더 낫습니다. –

2

이 스크립트해야 출력 최고 기록 너를위한 깔끔한 테이블. SQL 쿼리에 대한 OMG Ponies에게 감사드립니다.

<?php 
$dbhost = 'localhost'; // Database Host 
$dbuser = 'user';  // Database User 
$dbpass = 'password'; // Database Password 
$dbname = 'database'; // Database Name 

$db = mysql_connect($dbhost, $dbuser, $dbpass); 
mysql_select_db($dbname, $db); 

$limit = 10; // The number of users to show in the top highscores. Set to 0 to show all 

$sql = 'SELECT u.user, 
     SUM(s.runtime) AS total_run_time, 
     SUM(s.monsterskilled) AS total_monsters_killed, 
     SUM(s.profit) AS total_profit, 
     SUM(s.tasks) AS total_tasks, 
     SUM(s.xpgain) AS total_xp_gained 
     FROM USERS u 
     JOIN SESSION s ON s.userid = u.userid 
     GROUP BY u.user 
     ORDER BY total_run_time DESC'; 

if ($limit > 0) { 
    $sql .= ' LIMIT '.$limit; 
} 

$get_scores = mysql_query($sql); 
$scores = array(); 

$rank = 0; 
while($score = mysql_fetch_array($get_scores)) { 
    ++$rank; 
    $scores[] = '<td>'.$rank.'</td><td>'.$score['user'].'</td><td>'.$score['total_run_time'].'</td><td>'.$score['total_monsters_killed'].'</td><td>'.$score['total_profit'].'</td><td>'.$score['total_tasks'].'</td><td>'.$score['total_xp_gained'].'</td>'; 
} 

echo '<table><tbody>'; 
echo '<tr><td>Place</td><td>Username</td><td>Total Run Time</td><td>Total Monsters Killed, Total profit</td><td>Total tasks</td><td>Total Exp Gain</td></tr><tr>'; 
echo implode('</tr><tr>', $scores); 
echo '</tr></tbody></table>'; 
?> 
+0

+1 : 대답은 PHP'ifying 내 대답 –

+0

내 대답을 단순화 주셔서 감사합니다 :). – cdog5000