简体   繁体   中英

php/mysql : top 10 most scores by a member

I am making a scoreboard from a table where members details are stored in one table and scores are stored in another with members foreign keys. I know that I can show the leaderboard with:

$lbquery = mysql_query("SELECT mid, SUM( score ) AS count FROM `memberscores` GROUP BY mid ORDER BY count DESC");
$lbrow = mysql_fetch_array($lbquery);

$memid = $lbrow["mid"];
$memscore = $lbrow["count"];

    $memquery = mysql_query("SELECT firstname, lastname FROM `members` WHERE `mid`=".$memid);
    $memrow = mysql_fetch_array($memquery);
    $fname = $memrow["firstname"];
    $lname = $memrow["lastname"];

echo $lname." ".$fname." = "$memscore;

But I am confused how will show the first ten as it seems that may I have to use a loop to show the first ten in a table. but not sure how it will be used.

I think that you want a simple join:

SELECT m.mid, m.firstname, m.lastname, SUM(s.score) cnt 
FROM memberscores s 
INNER JOIN members m ON m.mid = s.mid
GROUP BY m.mid, m.firstname, m.lastname 
ORDER BY cnt DESC
LIMIT 10

This generates a resultset the top 10 users by total score, that includes the each user's first and last name. You can then fetch the resultset row by row and display the results in your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM