SELECT t4.orgName,
t3.projectName,
t3.Partner,
t1.type,
COUNT(DISTINCT t1.imei) AS count
FROM `t_teminal` AS t1
LEFT JOIN `t_orgcode_orgid_rela` AS t2
ON t1.orgid = t2.orgId
LEFT JOIN `t_org_code` AS t3
ON t2.topOrganizationCode = t3.topOrganizationCode
LEFT JOIN `t_organization` AS t4
ON t1.orgid = t4.orgId
GROUP BY t1.orgid
聯表查詢會涉及到多個表的操作, 在索引的利用上會受限制. 上面的命令執行時間720s
以上面為例, 因為join查詢的實現原理[MySQL 的Join及底層實現原理], 導致驅動表t1表的索引失效。而t1表的是最龐大的表, 約有50萬行數據, 而其他表只是幾百行的配置信息表.
所以利用t1表的索引是性能的關鍵.
由於統計中有groupby and count的需求,通過t1表即可實現, 順勢使用了子查詢, 先處理完t1,再去匹配信息.
這種思路很簡單,但應該對各種業務導向的報表查詢都有幫助,.
下面的命令執行時間3.6s
SELECT t4.orgName, t3.projectName, t3.Partner, t1.type, t1.count FROM ( SELECT orgid, type, COUNT(DISTINCT imei) AS count FROM `t_teminal` GROUP BY orgid ) AS t1 LEFT JOIN `t_orgcode_orgid_rela` AS t2 ON t1.orgid = t2.orgId LEFT JOIN `t_org_code` AS t3 ON t2.topOrganizationCode = t3.topOrganizationCode LEFT JOIN `t_organization` AS t4 ON t1.orgid = t4.orgId
