2014-05-07 69 views
1

這是我的查詢,但需要很長時間才能完成。得到記錄中有1個以上孩子的家庭數

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

桌子在哪裏? – user3470953

+0

是的,「兒童」不是英文單詞:)。 – Michal

+0

你對「家庭」和「兒童」有什麼指標? –

回答

2

您的查詢可能會正確的索引正常工作。我建議以下兩種:

create index families_fsc_unitid on families(family_status_cat_id, unit_id); 
create index children_familyid on children(family_id); 
+0

你知道關於索引的好文章嗎?或者一個好的拇指規則... –

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 

你會的,當然,需要在其他加回我省略的條件。