我的代码在这里添加了属于该配置文件的所有成员的总和。我是这样做的,我只想知道一些其他方法来加快速度。
我在这里有相关表格Municipality,Barangay,Purok,family_profile,family_members订购他们的关系。
SELECT f.family_id,f.family_code,f.lname,f.fname,f.mname,f.exname,f.remark,p.*,b.*,m.*,
(SELECT SUM(member_id!=0) from family_members WHERE family_id=f.family_id) AS MEMCOUNT
from family_profile f
LEFT join purok p on f.home_address=p.purok_id
LEFT join barangay b on p.brgy_id=b.brgy_id
LEFT join municipality m on b.mun_id=m.mun_id
where
f.family_id!=0 AND
family_code!=''
ORDER BY
mun_name,brgy_name,purok_name,f.lname,f.fname
答案 0 :(得分:1)
是,在此查询中:
SELECT
f.family_id,
f.family_code,
f.lname,
f.fname,
f.mname,
f.exname,
f.remark,
p.*,
b.*,
m.*,
(
SELECT SUM(member_id!=0)
FROM family_members
WHERE
family_id = f.family_id
) AS MEMCOUNT
FROM family_profile f
LEFT JOIN purok p on f.home_address=p.purok_id
LEFT JOIN barangay b on p.brgy_id=b.brgy_id
LEFT JOIN municipality m on b.mun_id=m.mun_id
WHERE
f.family_id != 0
AND family_code != ''
ORDER BY
mun_name,
brgy_name,
purok_name,
f.lname,
f.fname
您正在为每个返回的行计算SUM。这不是优化的。这个想法是通过将其设为记录集来计算一次:
SELECT
f.family_id,
f.family_code,
f.lname,
f.fname,
f.mname,
f.exname,
f.remark,
p.*,
b.*,
m.*,
MEMCOUNT.cnt AS MEMCOUNT
FROM family_profile f
LEFT JOIN purok p on f.home_address=p.purok_id
LEFT JOIN barangay b on p.brgy_id=b.brgy_id
LEFT JOIN municipality m on b.mun_id=m.mun_id
LEFT JOIN
(
SELECT family_id, SUM(member_id!=0) AS cnt
FROM family_members
GROUP BY family_id
) AS MEMCOUNT ON MEMCOUNT.family_id = f.family_id
WHERE
f.family_id != 0
AND family_code != ''
ORDER BY
mun_name,
brgy_name,
purok_name,
f.lname,
f.fname