用JOIN查询慢

时间:2014-03-03 08:27:47

标签: php mysql

为什么我的查询需要大约2分钟来处理?

我需要从8表中获取属性。

如何加入这些表并快速查询?

我想加入这些表的原因是因为我想从用户输入progCode获取fetchAll(PDO :: FETCH_ASSOC)

这是我的疑问:

"SELECT DISTINCT a.`ProgCode`, a.`Program` 
   FROM (select `i`.`name` AS `LC`,`f`.`name` AS `Intake`,`a`.`student_id` 
   AS `student_id`,`b`.`matricNo` 
   AS `matricNo`,`b`.`name` 
   AS `Nama`,`a`.`sem_id` 
   AS `sem_id`,`c`.`name` 
   AS `Sessi`,`e`.`code` 
   AS `ProgCode`,`e`.`name` 
   AS `Program`,`a`.`sub_id` 
   AS `sub_id`,`d`.`code` 
   AS `SubCode`,`d`.`name` 
   AS `Subject`,`a`.`grade` 
   AS `grade`,`h`.`credit` 
   AS `CurrentCreditHour`,`g`.`totalcredit` 
   AS `TotalCreditHour`,`g`.`gpa` 
   AS `GPA`,`g`.`cgpa` 
   AS `CGPA` from ((((((((`admin_sub_mark` `a` join `enrl_student` `b`) 
     join `struc_session` `c`) 
     join `struc_session` `f`) 
     join `struc_subject` `d`) 
     join `struc_program` `e`) 
     join `admin_sem_wise_cgpa` `g`) 
     join `admin_sem_wise_gpa` `h`) 
     join `struc_learningcentre` `i`) 
  where ((`b`.`id` = `a`.`student_id`) 
  and (`d`.`id` = `a`.`sub_id`) 
  and (`c`.`id` = `a`.`sem_id`) 
  and (`e`.`id` = `b`.`program_id`) 
  and (`f`.`id` = `b`.`intake_id`) 
  and (`i`.`id` = `b`.`learningCenter_id`) 
  and (`a`.`student_id` = `g`.`student_id`) 
  and (`a`.`sem_id` = `g`.`sem_id`) 
  and (`h`.`student_id` = `g`.`student_id`) 
  and (`h`.`sem_id` = `g`.`sem_id`)) order by `b`.`name`) a  
  ORDER BY `Program` ASC"

这是我的解释查询:

ID | select_type |表|类型| possible_keys |关键| key_len | ref |行|额外

1 |简单| g |所有| NULL | NULL | NULL | NULL | 6049 |使用临时;                                                           使用filesort

1 |简单| h |所有| NULL | NULL | NULL | NULL | 6055 |使用where |

1 |简单| c | eq_ref |主要|主要| 257 | educate_aeu2.g.sem_id 1

1 |简单| b | eq_ref |主要|主要| 257 | educate_aeu2.h.student_id 1使用where

1 |简单| f | eq_ref | PRIMARY |主要| 257 | educate_aeu2.b.intake_id 1

1 |简单| e | eq_ref |主要|主要| 257 | educate_aeu2.b.program_id 1

1 |简单|我| eq_ref |主要|主要| 257 | educate_aeu2.b.learningCenter_id 1

1 |简单| a | ALL | NULL | NULL | NULL | NULL | 17077 |使用何处

1 |简单| d | eq_ref |主要|主要| 257 | educate_aeu2.a.sub_id 1

1 个答案:

答案 0 :(得分:0)

你正在检索内部选择中的很多字段并进行排序,然后忽略大部分字段并进行另一种排序。这会浪费时间

快速清理代码可以: -

SELECT DISTINCT 
   e.code AS ProgCode,
   e.name AS Program
FROM admin_sub_mark a 
JOIN enrl_student b ON b.id = a.student_id
JOIN struc_session c ON c.id = a.sem_id
JOIN struc_session f ON f.id = b.intake_id
JOIN struc_subject d ON d.id = a.sub_id
JOIN struc_program e ON e.id = b.program_id
JOIN admin_sem_wise_cgpa g ON a.student_id = g.student_id AND a.sem_id = g.sem_id
JOIN admin_sem_wise_gpa h ON h.student_id = g.student_id AND h.sem_id = g.sem_id
JOIN struc_learningcentre i ON i.id = b.learningCenter_id
ORDER BY e.name ASC

不确定是否需要访问所有表格。

你还有哪些索引在桌子上?如果像这样的查询运行缓慢,那么罪魁祸首通常是索引,但不知道它们是什么(或者更好,来自EXPLAIN的输出),我们将很难提供任何有用的帮助