doumengjing1500 2018-07-23 16:30
浏览 103

为什么循环中的查询非常慢

I don't have a enough experience in mysql with php, but am trying to develop a school report card, am trying to query the students, with their exams, subjects and marks. In this case I have three loops. the First loop is for the students I use it to get the student's ID, the second loop is for the exam, i use it to get the exam ID and the last is for subject I use it to get the subject ID, i need all this IDs in order to get the marks for each student per exam per subject. Bellow are the loops;

foreach ($students as $student_row){ //get each student's ID
 $studentID = $student_row['studentID'];
       foreach ($allExams as $allExam) { //get each exam's ID
       $examID = $allExam['examID'];
            foreach ($subjects as $subject){ //get each subject's ID
               $subjectID = $subject['subjectID'];

$obtained_mark_query = $this->db->query("select * from mark
            where mark.studentID = '$studentID' && mark.examID = '$examID' && 
            mark.subjectID = '$subjectID'")->row()->mark; //to get mark for each student per exam per subject
                        }

              }

}

I don't know what's really the problem but this loop takes really long, it takes 26 second to return all the students in a specific class, there are only 23 students in a class, four exams, and five subjects, so am wondering what it'll really be when there are more than those students. Please any idea why it's behaving like this, any idea i can use other than loops.

  • 写回答

2条回答 默认 最新

  • duanhuchang5056 2018-07-23 16:42
    关注

    There are 2 main issues in your code's logic:

    1. You are selecting every field with SELECT * FROM which is highly inefficient, try selecting only the fields you are going to use
    2. You are querying in your 3rd nested loop, so instead of querying it once, you are doing 1 query per student, per exam, per subject (like 23 * 4 * 5 = 460 queries)

    The solution is to refactor your code, your db, and fetch that information in a simple query, then iterate through the returned records and handle the information server side.

    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探