![](/img/trans.png)
[英]Linking a table to a second table and pulling data from the first one to the second one multiple times
[英]Pulling data from a fairly large table multiple times is going slow
我目前正在我的网站上提供一个免费的测试功能,每个用户可以参加其中一个测试,看看他们的高分或其他什么。
我有一个经历每个测试的foreach并检查每个学生获得的最高年级。 保存测试的表格正在推动15,000行数据。
这大致是我所拥有的:
foreach(testList as $test){
SELECT saved_grade FROM system_saved
WHERE account_id = {{account_id}}
AND test_id = {{test_id}}
Order By saved_grade DESC
LIMIT 0, 1
}
它要求每个测试必须扫描整个表格,以便每次都找到最高等级。
您不需要单独选择每个测试。 假设对于每个进行测试的人来说,account_id是唯一的,并且saved_grade不是一个字符串,你应该能够做到这一点
SELECT MAX(saved_grade)
FROM system_saved
WHERE account_id = {{account_id}}
AND test_id = {{test_id}}
不要循环; 使用一个查询。 这将检索每个学生的最佳成绩,由学生订购,然后通过测试。
SELECT account_id, test_id, MAX(saved_grade) as `best_grade`
FROM system_saved
GROUP BY account_id DESC, test_id DESC
要在该学生的任何测试中获得最佳成绩,请使用以下内容:
SELECT account_id, MAX(saved_grade) as `best_grade`
FROM system_saved
GROUP BY account_id DESC
编辑:如果你想知道他们获得最高分的测试,你可以这样做:
SELECT account_id, test_id, saved_grade
FROM system_saved WHERE (account_id, saved_grade) IN (
SELECT account_id, MAX(saved_grade) as `best_grade`
FROM system_saved
GROUP BY account_id DESC)
你可能应该使用max():
foreach(testList as $test){
SELECT max(saved_grade) FROM system_saved
WHERE account_id = {{account_id}}
AND test_id = {{test_id}}
}
您正在寻找的解决方案是GROUP BY和agggregation函数:
SELECT account_id, test_id, max( saved_grade ) as highest_grade
FROM system_saved
GROUP BY account_id, test_id
同时为(account_id, test_id, saved_grade)
创建索引,以获得比未索引数据更好的性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.