mysql查询内连接需要40到45秒

时间:2014-09-12 15:29:40

标签: mysql performance

SELECT  a.gid, a.qid,
        SUM(a.result = 1) first_attempt_correct,
        SUM(a.result = 0) first_attempt_incorrect
        FROM maf_game_stats a
                LEFT JOIN
                (
                    SELECT USERID, gid, QID, MIN(ACCESSTIME) min_date
                    FROM maf_game_stats
                    GROUP BY USERID, gid, qid
                )  b ON a.USERID = b.USERID AND
                    a.gid = b.gid AND
                    a.qid = b.qid AND
                    a.ACCESSTIME = b.min_date
        WHERE   a.gid ='2'
        AND a.ACCESSTIME >= '2014-09-01' AND a.ACCESSTIME < '2014-09-10' + INTERVAL 1 DAY 
        GROUP BY a.gid, a.qid

以上给定的查询执行时间40到50秒我怎样才能打破这些查询

3 个答案:

答案 0 :(得分:0)

添加

在哪里gid =&#39; 2&#39;

到内部左连接查询。没有它,你正在查询所有&#34; gid&#34;值。所以,因为你的外部查询只关心&#34; gid = 2&#34;,谁在乎你是否有&#34; gid = 1,3,2903,甚至389433&#34;在内部结果集中。有相同的,它应该是瞬间的。

此外,您可能需要将日期条件应用于内部查询,但不确定您要从中获取的确切内容。

答案 1 :(得分:0)

我建议使用not exists写一下,然后添加一些索引。查询是:

SELECT  gs.gid, gs.qid,
        SUM(gs.result = 1) first_attempt_correct,
        SUM(gs.result = 0) first_attempt_incorrect
FROM maf_game_stats gs
WHERE gs.gid ='2' AND
      gs.ACCESSTIME >= '2014-09-01' AND gs.ACCESSTIME < '2014-09-10' + INTERVAL 1 DAY AND
      NOT EXISTS (SELECT 1
                  FROM maf_game_stats gs2
                  WHERE gs2.gid = gs.gid and gs2.qid = gs.qid and gs2.AccessTime > gs2.AccessTime
                 )
GROUP BY gs.gid, gs.qid;

索引为:maf_game_starts(gid, accesstime, qid, result)maf_game_stats(gid, qid, AccessTime)

答案 2 :(得分:0)

最终解决方案如下:

SELECT  a.gid, a.qid,
        SUM(a.result = 1) first_attempt_correct,
        SUM(a.result = 0) first_attempt_incorrect
        FROM maf_game_stats a
                INNER JOIN
                (
                    SELECT USERID, gid, QID, MIN(ACCESSTIME) min_date
                    FROM maf_game_stats
                    WHERE   gid ='2' 
                    AND ACCESSTIME >= '2014-09-01' AND ACCESSTIME < '2014-09-12' + INTERVAL 1 DAY
                    GROUP BY USERID, gid, qid
                )  b ON a.USERID = b.USERID AND
                    a.gid = b.gid AND
                    a.qid = b.qid AND
                    a.ACCESSTIME = b.min_date
        WHERE   a.gid ='2'
        AND a.ACCESSTIME >= '2014-09-01' AND a.ACCESSTIME < '2014-09-12' + INTERVAL 1 DAY 
        GROUP BY a.gid, a.qid