【发布时间】:2019-02-14 08:50:02
【问题描述】:
我正在尝试查找在问题“平台”(id 1)上回答“facebook”的所有客户
每个客户都有问卷,我正在尝试寻找在“平台”问题上回答“facebook”的客户,问题的 id 是固定的,例如问题表中的“平台”id 是 1,“年龄”是 2 等等. 每个问卷都有不同的问题集,例如问卷 id 1 有问题“平台”,但答案将通过选择框而不是文本框输入(因此需要 answer_option 表),问卷 id 2 可能没有问题平台和等。将来自搜索屏幕的参数是问卷 id 和回答问题“平台”的文本。
这就是我目前所拥有的......
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.id = 1 and answers.answer LIKE '%facebook%');
如果您注意到 question.id 将始终为 1,因为我只是在平台中寻找答案,这是我屏幕的特殊功能。 我尝试了 1 - 20 行数据,它可以工作,但如果数据变得像 20,000 行一样大,它永远不会返回我已经尝试过的真实数据的记录,查询需要永远取消它。由于问题 id 已经是常量并且问卷 id 来自搜索参数,我想也许我不需要加入不必要的表,而且我认为放置索引不会有帮助,因为我有一个通配符参数?(不确定) ,但我不知道如何。
示例数据和预期结果
Customer:
id:1,
family_name: "smith",
first_name: "smith",
..
Customer:
id:2,
family_name: "david",
first_name: "david",
..
QuestionnaireAnswer:
id: 20199,
questionnaire_id: 4,
answerable_type: "Customer",
answerable_id: "1",
QuestionnaireAnswer:
id: 20200,
questionnaire_id: 5,
answerable_type: "Customer",
answerable_id: "2",
Questionnaire:
id: 4,
name: "Survey for Psychology Students",
group_code: "10",
Questionnaire:
id: 5,
name: "Survey for Students",
group_code: "10",
Question:
id: 1,
name: "platform",
answer_type: "08", //selectbox
default_text: nil,
sequence: 1,
question_valid: true,
disabled: false,
questionnaire_id: 5,
...
Question:
id: 2,
name: "school",
answer_type: "01", //textbox
default_text: nil,
sequence: 2,
question_valid: true,
disabled: false,
questionnaire_id: 5,
...
Question:
id: 3, // I said the the id for platform is fixed but this time this question is textbox inputted so it is different
name: "platform",
answer_type: "01", //text
default_text: nil,
sequence: 1,
question_valid: true,
disabled: false,
questionnaire_id: 5,
...
Question:
id: 4,
name: "town",
answer_type: "01", //textbox
default_text: nil,
sequence: 2,
question_valid: true,
disabled: false,
questionnaire_id: 4,
...
Answer:
id: 1,
question_id: 3,
answer_option_id: nil,
answer: "facebook",
questionnaire_answer_id: 19585,
created_at: Wed, 13 Feb 2019 21:43:15 JST +09:00,
updated_at: Wed, 13 Feb 2019 21:43:15 JST +09:00,
member_id: nil>,
任何帮助将不胜感激。
【问题讨论】:
-
更新您的问题添加适当的(最小)数据样本和预期结果..作为文本(不是图像)..
-
好的,我会尝试添加更多谢谢。
-
LIKE '%facebook%'必须进行完整搜索,因为该模式无法被索引。你能做answer_options.answer = 'facebook'吗?然后确保该列已编入索引。 -
@barmar ,糟糕,这是错误的查询,我编辑了。从技术上讲,如果问卷指示问题平台的输入是选择框,我可以这样做,但有时问卷必须要求问题“平台”的文本框输入
-
我认为你不需要加入
answer_options。
标签: mysql join inner-join sql-tuning