MySQL - 我的视图很慢

时间:2017-05-07 11:43:32

标签: mysql join view

我有4张桌子:

  • 学生 with over 7000 records
  • 教师 with over 600 records
  • 大学 with over 30 records
  • Lessons_Meta with over 10000 records

学生列:

id | student_number | name


教师列:

id | teacher_number | name


大学列:

id | name


Lessons_Meta 列:

id | lesson_code | lesson_name | student_id | teacher_id | university_id


我的观点是:

CREATE VIEW `view_lessons` AS
SELECT
        *,
        (SELECT `name` FROM `students` WHERE `students`.`id` = `lessons_meta`.`student_id` LIMIT 1) AS "student_name",
        (SELECT `name` FROM `teachers` WHERE `teachers`.`id` = `lessons_meta`.`teacher_id` LIMIT 1) AS "teacher_name",
        (SELECT `name` FROM `universities` WHERE `universities`.`id` = `lessons_meta`.`university_id` LIMIT 1) AS "university_name"
FROM `lessons_meta`


我的查询是:

SELECT * FROM `view_lessons` LIMIT 20

20秒后,显示此查询已完成!如何减少这个时间负荷?

1 个答案:

答案 0 :(得分:1)

将您的视图更改为此

CREATE VIEW `view_lessons` AS
SELECT L.*,  S.`name` AS student_name, T.`name` AS teacher_name, U.`name` AS university_name
FROM `lessons_meta` L
INNER JOIN `students` S ON S.`id` = L.`student_id`
INNER JOIN `teachers` T ON T.`id` = L.`teacher_id` 
INNER JOIN `universities` U ON U.`id` = L.`university_id`
  • lessons_meta表格中,在student_idteacher_iduniversity_id
  • 上添加索引
  • 在所有表格上,确保id列已正确编入索引,通常它们应该是唯一的/ PK