我有4个表:发货(200K记录),商店(45个记录),product_stores(8K记录),地区(698个记录)。以下查询需要很长时间才能执行(12秒):
SELECT `s`. * , `p`.`productCode` , `p`.`productName` , `st`.`name` AS `storeName` , `d`.`name` AS `districtName`
FROM `shipments` AS `s`
JOIN `product_stores` AS `p` ON s.productStoreId = p.id
JOIN `stores` AS `st` ON s.storeId = st.id
LEFT JOIN `districts` AS `d` ON s.districtId = d.id
WHERE (s.storeId IN (1, 2, 3, 4, 6, 9, 14, 16, 22, 26, 30))
GROUP BY `s`.`id`
ORDER BY `s`.`id` DESC
LIMIT 100
EXPLAIN查询返回以下结果:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE st ALL PRIMARY NULL NULL NULL 45 Using where; Using temporary; Using filesort
1 SIMPLE s ref fk_shipments_stores1_idx,fk_shipments_product_stor... fk_shipments_stores1_idx 4 st.id 482
1 SIMPLE p eq_ref PRIMARY PRIMARY 4 s.productStoreId 1
1 SIMPLE d eq_ref PRIMARY PRIMARY 4 s.districtId 1
(我正在使用mysql 5.0.95)
这是表结构:
答案 0 :(得分:1)
您的查询速度很慢,因为您的查询加入策略需要过多的I / O
让我为您的查询I / O草拟计算,以便理解如下:
1. JOIN shipments (200K records) and product_stores (8K records)
200K x 8 K = 1600K I/O
2. Then, JOIN to stores (45 records)
1600K x 45 = 75000K I/O
3. Then, JOIN to districts (698 records)
75000K x 698 = 50256000K I/O
4. Then, Filter the result (by storeId), so need to read the result I/O again
50256000K + 50256000K = **100512000K I/O (TOTAL I/O)**
So, total I/O on memory of your query is 100512000K I/O.
要提高查询效果,您需要重新考虑加入计划/策略的查询
例如:
1. Read shipments (200K records) and Filter storeId (assume: result is 8 record)
200K + 8 = 208K I/O
2. Then, JOIN to product_stores (8K records)
208K x 8K = 1664K I/O
3. Then, JOIN to stores (45 records)
1664K x 45K = 74880K I/O
4. Then, finally JOIN to districts (698 records).
74880K + 698 = **52266240 I/O (TOTAL I/O)**
So, total I/O on memory of your query is 52266240 I/O. (greatly reduce I/O then ever)
因此,您可以通过以上方式提高查询效果。
我希望它可以帮助你。
答案 1 :(得分:0)
我只是在尝试解决方案。希望这可以减少执行时间
SELECT `s`. * , `ps`.`productCode` , `ps`.`productName` , `st`.`name` AS `storeName` , `d`.`name` AS `shipToDistrictName`
FROM `shipments` AS `s`
JOIN `product_stores` AS `ps` ON s.productStoreId = ps.id
JOIN `stores` AS `st` ON (s.storeId = st.id AND s.storeId IN (1, 2, 3, 4, 6, 9, 14, 16, 22, 26, 30))
LEFT JOIN `districts` AS `d` ON s.shipToDistrictId = d.id
GROUP BY `s`.`id`
ORDER BY `s`.`id` DESC
LIMIT 100
这会将记录数限制为只有那些只有那些需要的记录,并进一步加入减少数量的记录,从而减少执行时间。
希望它有所帮助...