MySQL IN条件子查询

时间:2014-08-08 09:30:25

标签: mysql sql performance where where-in

我有一个问题和答案列表以及根据正确答案的百分比过滤问题的选项。所以我使用以下查询列表:

SELECT 
question_id, 
text
FROM 
test_answers LEFT JOIN test_questions ON test_questions.id = test_answers.question_id 
LEFT JOIN test_categories ON test_questions.`category_id` = test_categories.id 
WHERE `question_id` IN(question IDS) 
GROUP BY `question_id` 
ORDER BY `question_id` DESC;

并使用另一个查询来查找问题IDS,其中给定范围内的正确答案的百分比。查询如下:

SELECT q1.question_id FROM (
        SELECT test_answers.question_id AS question_id, 
        SUM( IF( test_answers.correct_answer =1, 1, 0 ) ) AS correct_answers, 
        SUM( IF( test_answers.correct_answer !=1, 1, 0 ) ) AS incorrect_answers, 
        round( ( SUM( IF( test_answers.correct_answer =1, 1, 0 ) ) / ( SUM( IF( test_answers.correct_answer =1, 1, 0 ) ) + SUM( IF( test_answers.correct_answer !=1, 1, 0 ) ) ) *100 ) , 2 ) AS percentage 
        FROM test_replies 
        JOIN test_answers ON test_replies.answer_id = test_answers.id 
        GROUP BY test_answers.question_id 
        HAVING percentage between 80 and 89 AND correct_answers >25
) AS q1

现在的问题是,第二个查询返回了近4000个问题ID,它将在不久的将来增加,可能会变为10k或更多。因此,我非常希望优化查询,因为它会对性能产生很大影响。有人能建议一个更好的方法吗?

1 个答案:

答案 0 :(得分:0)

尝试加入而不是IN,看看是否有帮助。 (sql未经过测试)

SELECT 
    ta.question_id, text
FROM 
    (
        SELECT test_answers.question_id AS question_id, 
        SUM( IF( test_answers.correct_answer =1, 1, 0 ) ) AS correct_answers, 
        SUM( IF( test_answers.correct_answer !=1, 1, 0 ) ) AS incorrect_answers, 
        round( ( SUM( IF( test_answers.correct_answer =1, 1, 0 ) ) / ( SUM( IF( test_answers.correct_answer =1, 1, 0 ) ) + SUM( IF( test_answers.correct_answer !=1, 1, 0 ) ) ) *100 ) , 2 ) AS percentage 
        FROM test_replies 
        JOIN test_answers ON test_replies.answer_id = test_answers.id 
        GROUP BY test_answers.question_id 
        HAVING percentage between 80 and 89 AND correct_answers >25
    ) AS q1
INNER JOIN 
    test_answers ta USING (question_id) 
LEFT JOIN 
    test_questions ON test_questions.id = ta.question_id 
LEFT JOIN 
    test_categories ON test_questions.`category_id` = test_categories.id 
GROUP BY 
    ta.question_id`
ORDER BY 
    ta.question_id DESC;