1

我有一个具有以下列名称的表: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

请建议我如何优化查询。

4

3 回答 3

4
SELECT  audit_name,
        SUM(audit_choice = 'Passed') AS passed,
        SUM(audit_choice = 'Failed') AS failed
FROM    audit
GROUP BY
        audit_name
于 2012-06-05T11:43:28.547 回答
2

我还建议将诸如“Passed”和“Failed”之类的字符串值移出表,并改用整数标识符 - 它们的比较速度比字符串快得多。

于 2012-06-05T11:44:02.090 回答
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
于 2012-06-05T11:48:57.720 回答