需要查询出总数、成功数和失败数渲染到页面,43W 条数据中查询出 600 多条需要查询 9s 以上。后来给所有 where 以及 order by 的字段加上了索引,用 EXPLAIN 检查发现创建了临时表和全表扫描,遂把 distinct 去掉,但效果还是不理想。想请教下还应该如何进行优化呢? 初始 sql 如下: SELECT t.business_no AS businessNo, t.service_type AS serviceType, ( SELECT count(d.datagram_id) FROM t_issue_plat_datagram d WHERE t.business_no = d.business_no ) AS limitCount, ( SELECT count(b.datagram_id) FROM t_issue_plat_datagram b WHERE t.business_no = b.business_no AND b.batch_status = '2' ) AS sucessCount, ( SELECT count(c.datagram_id) FROM t_issue_plat_datagram c WHERE t.business_no = c.business_no AND c.batch_status = '3' ) AS falseCount FROM ( SELECT DISTINCT g.business_no, g.service_type FROM t_issue_plat_datagram g WHERE 1 = 1 ORDER BY g.updated_date DESC ) t 修改后的 sql: SELECT t.business_no AS businessNo, t.service_type AS serviceType, ( SELECT count(d.datagram_id) FROM t_issue_plat_datagram d WHERE t.business_no = d.business_no ) AS limitCount, ( SELECT count(b.datagram_id) FROM t_issue_plat_datagram b WHERE t.business_no = b.business_no AND b.batch_status = '2' ) AS sucessCount, ( SELECT count(c.datagram_id) FROM t_issue_plat_datagram c WHERE t.business_no = c.business_no AND c.batch_status = '3' ) AS falseCount FROM t_issue_plat_datagram t GROUP BY t.business_no ORDER BY t.updated_date
SELECT businessNo, serviceType, SUM(s.num), SUM( CASE WHEN s.stauts = '2' THEN s.num END ), SUM( CASE WHEN s.stauts = '3' THEN s.num END ) FROM ( SELECT t.business_no AS businessNo, t.service_type AS serviceType, t.batch_status AS stauts, COUNT(t.datagram_id) AS num, updated_date AS date FROM t_issue_plat_datagram t GROUP BY t.business_no, t.batch_status ) s GROUP BY s.businessNo ORDER BY s.date
SELECT business_no, service_type, COUNT(1) as limitCount, COUNT(CASE WHEN batch_status = '2' THEN 1 ELSE 0 END) as successCount, COUNT(CASE WHEN batch_status = '3' THEN 1 ELSE 0 END) as falseCount, FROM t_issue_plat_datagram GROUP BY business_no ORDER BY updated_date
SELECT business_no, service_type, COUNT(1) as limitCount, COUNT(CASE WHEN batch_status = '2' THEN 1 ELSE NULL END) as successCount, COUNT(CASE WHEN batch_status = '3' THEN 1 ELSE NULL END) as falseCount, FROM t_issue_plat_datagram GROUP BY business_no ORDER BY updated_date