所以这是我的数据库结构的图像:
基本上它是一个测验应用程序,其中每个问题和测验都有一个类别(因为还有测验类别混合 - 其中包括几个类别的问题)。每次用户播放新测验时,测验表中都会生成一个新条目 - 记录用户,类别,分数以及测验的开始和结束时间。
我需要一个查询,其中我显示每个用户和类别的最新分数。 (很高兴:也是每个用户和类别的平均分数)
最后应该看起来像。显然我已经有一个查询,但它并没有真正起作用,因为Max Mustermann只显示了一个结果,但实际上有4个类别的结果。我真的不知道为什么所有其他用户都会显示他们播放的结果,也许这是因为他们每个类别只打了一个测验。但Max Mustermann只播放了一次“混合”类别,但没有显示。
这是我目前使用的代码:
$query_scores_per_cat_per_user = "
SELECT category, t1.scores AS scores
FROM categories
left JOIN quizzes as t1 ON categories.id=t1.FK_categories
left JOIN quizzes AS t2
ON t1.FK_users = t2.FK_users
AND t1.end_timestamp < t2.end_timestamp
WHERE t2.FK_users IS NULL
and t1.fk_categories = ".$category_id." and t1.FK_users=".$all_users_id."
order by category ASC"
你可以帮我找错吗?我真的迷失在这里。
谢谢!
答案 0 :(得分:0)
您需要在第二个join
中包含该类别。
$query_scores_per_cat_per_user = "
SELECT category, t1.scores AS scores
FROM categories
left JOIN quizzes as t1 ON categories.id=t1.FK_categories
left JOIN quizzes AS t2
ON t1.FK_users = t2.FK_users
AND t1.FK_categories = t2.FK_categories
AND t1.end_timestamp < t2.end_timestamp
WHERE t2.FK_users IS NULL
and t1.fk_categories = ".$category_id." and t1.FK_users=".$all_users_id."
order by category ASC"
答案 1 :(得分:-1)
SELECT t2.UserName, category, Sum(t1.scores) AS scores, AVG(t1.scores)
FROM categories
left JOIN quizzes as t1 ON categories.id=t1.FK_categories
left JOIN quizzes AS t2
ON t1.FK_users = t2.FK_users
AND t1.end_timestamp < t2.end_timestamp
WHERE t2.FK_users IS NULL
and t1.fk_categories = ".$category_id." and t1.FK_users=".$all_users_id."
Group by t2.UserName, Category,
order by t1.Scores desc, category
我没试过..