使用几乎相同的子查询优化mySQL查询

时间:2014-11-07 10:57:01

标签: mysql

有没有办法优化以下查询?

SELECT s1.* FROM
(SELECT s.* 
FROM answer a, answer_item ai, sessions s
WHERE s.session_state='FINISHED' AND a.sessionId=s.id AND ai.answer=a.id
AND a.question=1001 AND ai.question_variant_id=1103) s1, 
(SELECT s.* 
FROM answer a, answer_item ai, sessions s
WHERE s.session_state='FINISHED' AND a.sessionId=s.id AND ai.answer=a.id
AND a.question=1003 AND ai.question_variant_id=1301) s2
WHERE s1.id=s2.id 

除了这些部分外,一切似乎都是一样的:

  1. a.question=1001 AND ai.question_variant_id=1103
  2. a.question=1003 AND ai.question_variant_id=1301

4 个答案:

答案 0 :(得分:2)

SELECT s.* 
FROM answer a
JOIN answer_item ai ON ai.answer=a.id
JOIN sessions s ON a.sessionId=s.id
WHERE s.session_state='FINISHED'
AND 
(
      a.question=1001 AND ai.question_variant_id=1103
   OR a.question=1003 AND ai.question_variant_id=1301
)

答案 1 :(得分:1)

检查以下优化查询。

SELECT  s.* FROM  FROM answer a, answer_item ai, sessions s
WHERE s.session_state='FINISHED' AND a.sessionId=s.id AND ai.answer=a.id
AND ( 
   (a.question=1001 AND ai.question_variant_id=1103)
   OR 
   (a.question=1003 AND ai.question_variant_id=1301)
)

答案 2 :(得分:1)

尝试这一次(JOINansweranswer_item两次):

SELECT s.* 
FROM answer a
JOIN answer_item ai ON ai.answer=a.id
JOIN sessions s ON a.sessionId=s.id
JOIN answer a2 ON s.id=a2.sessionId
JOIN answer_item ai2 ON ai2.answer=a2.id
WHERE s.session_state='FINISHED'
AND ( (a.question=1001 AND ai.question_variant_id=1103)
AND (a2.question=1003 AND ai2.question_variant_id=1301) )

答案 3 :(得分:1)

这似乎是在寻找回答这两个问题的会议(或其他)。我认为以下内容可能会为您提供所需的行。但是,您可能需要做更多工作才能获得正确的列:

  SELECT s.* 
  FROM answer a JOIN
       answer_item ai
       ON ai.answer = a.id JOIN
       sessions s
       ON a.sessionId = s.id
  WHERE s.session_state = 'FINISHED' AND
        (a.question = 1001 AND ai.question_variant_id = 1103 OR
         a.question = 1003 AND ai.question_variant_id = 1101
        )
  GROUP BY s.id
  HAVING SUM(a.question = 1001 AND ai.question_variant_id = 1103) > 0 AND
         SUM(a.question = 1003 AND ai.question_variant_id = 1101) > 0