这是我的查询,但需要很长时间才能完成。
SELECT count(*) AS count_all
FROM families
WHERE family_status_cat_id = 1374
AND (SELECT COUNT(*) FROM childrens WHERE family_id = families.id) > 1
AND unit_id IN (49,33,74,327,329,453,454,469,472,546,547)
有没有办法让它变得更好?
答案 0 :(得分:2)
您的查询可能正常使用正确的索引。我建议以下两点:
create index families_fsc_unitid on families(family_status_cat_id, unit_id);
create index children_familyid on children(family_id);
答案 1 :(得分:0)
HAVING
子句允许您过滤掉不符合某些聚合条件的行
select
count(*)
from families
inner join
(
SELECT
family_id
FROM childrens as c
group by family_id
having COUNT(*) > 1 -- more than one child in the family
) as MultiChild
on MultiChild.falily_id = families.id
当然,您需要在我省略的其他条件中加回。