优化5个内部联接

时间:2019-02-13 03:57:45

标签: mysql inner-join sql-tuning sql-optimization

我有一个客户表和调查表,都有调查表和答案,而调查表和问题表都有答案,我不知道问题是否首先在模型设计中出现,但是下面的查询返回了4000行客户在大约4分钟内对于sql和优化,我是一个非常初学者,对索引几乎一无所知。谁能帮我吗?

在下面的查询中,我正在寻找在“平台”问题中回答“ Facebook”的客户

我正在使用滑轨。这些是我的模特

客户类别

class Customer < ApplicationRecord

has_many :questionnaire_answers, as: :answerable

end

questionnaire_answer类

class QuestionnaireAnswer < ApplicationRecord

belongs_to :answerable, polymorphic: true
belongs_to :questionnaire
has_many :answers

end

调查问卷类

class Questionnaire < ApplicationRecord

has_many :questionnaire_answers, as: :answerable
has_many :questions

end

问题课

class Question < ApplicationRecord

has_many :answers
belongs_to :questionnaire
has_many :answer_options

end

answer_option类

class AnswerOption < ApplicationRecord

has_many :answers
belongs_to :question

end

answer类

class Answer < ApplicationRecord


belongs_to :question
belongs_to :answer_option
belongs_to :questionnaire_answer

end

我的sql

SELECT `customers`.* FROM `customers`
INNER JOIN `questionnaire_answers` 
ON `questionnaire_answers`.`answerable_id` = `customers`.`id` 
AND `questionnaire_answers`.`answerable_type` = 'Customer' 
INNER JOIN `questionnaires` 
ON `questionnaires`.`id` = `questionnaire_answers`.`questionnaire_id` 
INNER JOIN `questions` 
ON `questions`.`questionnaire_id` = `questionnaires`.`id` 
INNER JOIN `answers` 
ON `answers`.`question_id` = `questions`.`id` 
INNER JOIN `answer_options` 
ON `answer_options`.`id` = `answers`.`answer_option_id` 
WHERE (questions.name = 'platform' and answer_options.answer LIKE '%Facebook%')

mysql解释结果

    '1','SIMPLE','questionnaire_answers','ALL',NULL,NULL,NULL,NULL,'5','Using where'
'1','SIMPLE','customers','eq_ref','PRIMARY','PRIMARY','8','tech-consul_development.questionnaire_answers.answerable_id','1','Using where'
'1','SIMPLE','questionnaires','eq_ref','PRIMARY','PRIMARY','8','tech-consul_development.questionnaire_answers.questionnaire_id','1','Using where; Using index'
'1','SIMPLE','answers','ALL',NULL,NULL,NULL,NULL,'113','Using where; Using join buffer (Block Nested Loop)'
'1','SIMPLE','questions','eq_ref','PRIMARY','PRIMARY','8','tech-consul_development.answers.question_id','1','Using where'
'1','SIMPLE','answer_options','eq_ref','PRIMARY','PRIMARY','8','tech-consul_development.answers.answer_option_id','1','Using where'

1 个答案:

答案 0 :(得分:-1)

如果不是主键,请为WHERE子句之后的列创建索引。并尝试将数据很少的表放在SELECT子句的开头,并使用解释查询进行检查