如果您要返回的是所有重复项的总“计数”,但仅适用于在 APPROVED 和 CREATED_AT 上具有指定谓词的两行或多行的组织名称,那么您可以使用备用语句返回等价的结果:
SELECT SUM(c.cnt)
FROM ( SELECT COUNT(organization.ID) AS cnt
FROM organization o
WHERE o.NAME <> ''
GROUP
BY o.NAME
HAVING SUM(o.APPROVED = 0 AND o.CREATED_AT > '2012-07-31 04:31:08') > 1
) c
MySQL 可以利用一个合适的覆盖索引来满足这个查询,否则,这很可能是对组织表的全扫描。但它避免了两次引用组织表,并避免了 JOIN 操作。
此查询的一个合适的覆盖索引是:
ON organization (NAME, CREATED_AT, APPROVED, ID)
请注意,如果该ID
列保证为非 NULL(NOT NULL 约束或其表的 PRIMARY KEY,则可以避免引用该列,并且可以将该列排除在索引定义之外。)
SELECT SUM(c.cnt)
FROM ( SELECT SUM(1) AS cnt
FROM organization o
WHERE o.NAME <> ''
GROUP
BY o.NAME
HAVING SUM(o.APPROVED = 0 AND o.CREATED_AT > '2012-07-31 04:31:08') > 1
) c
EXPLAIN 输出显示此查询使用索引来满足查询,而不引用表中的任何数据块:
id select_type table type possible_keys key key_len ref rows Extra
-- ----------- ---------- ------ --------------- --------------- ------- ------ ------ --------------------------
1 PRIMARY <derived2> ALL (NULL) (NULL) (NULL) (NULL) 2
2 DERIVED o index organization_ix organization_ix 44 (NULL) 29 Using where; Using index