![](/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.