我使用以下查询来计算并显示某些测验的用户平均分
$query = 'SELECT AVG(answer) FROM quiz_answers WHERE id_user = '.$id_user.'';
$averagescore = mysql_query($query, $conn) or die(mysql_error());
$row = mysql_fetch_array($averagescore);
echo number_format($row['AVG(answer)'],3);
这部分工作正常,但在这个个人信息旁边,我还希望显示我们所有网站用户的前3个平均分数,比如一个小名人堂......
我尝试过以下代码:
$queryall = 'SELECT * FROM quiz_answers WHERE id_user IN (SELECT id_user FROM quiz_answers GROUP BY id_user HAVING COUNT(id_user) > 1)'
$groupresultsbyuser = mysql_query($query, $conn) or die(mysql_error());
$rows = mysql_fetch_array($groupresultsbyuser);
$numberofrowsperuser = mysql_num_rows($groupresultsbyuser);
我被困在这里..请帮助我找到一种方法让它发挥作用。
答案 0 :(得分:1)
假设您想要显示某些用户(例如用户名)以及高分,您可以按用户提取平均分数,然后加入您的用户表(为了论证,我' m调用users
并假设它有一个user_id
字段)
SELECT u.*, scores.avgScore
FROM users u
JOIN (
SELECT id_user, AVG(answer) AS avgScore
FROM quiz_answers
GROUP BY id_user
ORDER BY avgScore DESC LIMIT 3
) scores ON u.id_user = scores.id_user
答案 1 :(得分:1)
试试这个:
SELECT id_user,AVG(answer)
FROM quiz_answers
GROUP BY id_user
ORDER BY AVG(answer) DESC
LIMIT 3