优化mysql查询以选择值

时间:2012-06-05 11:39:51

标签: mysql sql group-by

我有一个包含以下列名的表:audit_name,audit_choice和“slno”作为自动增量主键,不用于输出数据。

audit_name可以重复,audit_choice值限制为某些值,如“Passed”,“Failed”。

我的查询预期输出是,获取每个“Audit_name”的“通过”计数和“失败”计数。

以下是我尝试的查询,但执行大约1,000条记录大约需要3-4分钟。

SELECT audit_name,
  (SELECT COUNT(*) AS Passed FROM audit AS p1
     WHERE p1.audit_name=p2.audit_name AND p1.audit_choice="Passed") AS Passed,
  (SELECT COUNT(*) AS Failed FROM audit AS p3
     WHERE p3.audit_name=p2.audit_name AND p2.audit_choice="Failed") AS Failed
  FROM audit AS p2
  GROUP BY audit_name

请建议我如何优化查询。

3 个答案:

答案 0 :(得分:4)

SELECT  audit_name,
        SUM(audit_choice = 'Passed') AS passed,
        SUM(audit_choice = 'Failed') AS failed
FROM    audit
GROUP BY
        audit_name

答案 1 :(得分:2)

我还建议将“Passed”和“Failed”等字符串值移出表格并使用整数标识符 - 它们的比较速度比字符串快得多。

答案 2 :(得分:1)

    SELECT  audit_name,
         SUM(if(audit_choice = 'Passed',1,0)) AS passed,
         SUM(if(audit_choice = 'Failed',1,0)) AS failed
    FROM    audit
    GROUP BY
    audit_name