このクエリを見てください:
SELECT
(SELECT COUNT(id) FROM result WHERE `mterm1` > r.mterm1 AND lesson_id = r.lesson_id) + 1 AS `pos_mt1_school`,
(SELECT COUNT(id) FROM result WHERE `mterm1` > r.mterm1 AND lesson_id = r.lesson_id AND class_id = r.class_id) + 1 AS `pos_mt1_class`,
(SELECT COUNT(id) FROM result WHERE `term1` > r.term1 AND lesson_id = r.lesson_id) + 1 AS `pos_t1_school`,
(SELECT COUNT(id) FROM result WHERE `term1` > r.term1 AND lesson_id = r.lesson_id AND class_id = r.class_id) + 1 AS `pos_t1_class`,
(SELECT COUNT(id) FROM result WHERE `mterm2` > r.mterm2 AND lesson_id = r.lesson_id) + 1 AS `pos_mt2_school`,
(SELECT COUNT(id) FROM result WHERE `mterm2` > r.mterm2 AND lesson_id = r.lesson_id AND class_id = r.class_id) + 1 AS `pos_mt2_class`,
(SELECT COUNT(id) FROM result WHERE `term2` > r.term2 AND lesson_id = r.lesson_id) + 1 AS `pos_t2_school`,
(SELECT COUNT(id) FROM result WHERE `term2` > r.term2 AND lesson_id = r.lesson_id AND class_id = r.class_id) + 1 AS `pos_t2_class`,
r.*, student.* FROM result r
LEFT JOIN lessons lesson ON r.lesson_id = lesson.id
LEFT JOIN students student ON r.student_id = student.id
LEFT JOIN classes class ON student.class_id = class.id
WHERE student.id = 217 ORDER BY lesson.id ASC
学生の試験の点数を表示したい。したがって、最初にテーブルから彼の結果(試験のスコア)を選択しresult
、次に参加lessons
してレッスン名を表示し、最後に彼のクラスと学校の各レッスンでの生徒の位置を計算します。(彼の試験のスコアに基づく)
このクエリは正常に機能しますが、実行には約2秒かかります。(パフォーマンスの問題)
そのクエリの最適化はありますか?(およびその副選択クエリの代替)