SELECT count( 0 ) FROM ( SELECT so.inventory_id AS dealUserId, so.inventory_name AS handlers, count( 0 ) AS secondNum, ( SELECT count( 0 ) FROM t_order_repair_item WHERE inventory_id = so.inventory_id ) AS totalCount FROM t_sub_order a LEFT JOIN t_order_repair_item so ON so.sub_order_id = a.sub_order_id WHERE a.repair_repeat = 1 AND so.inventory_id IS NOT NULL AND a.sls_name IN ( SELECT sls_name FROM t_sls_name WHERE sls_model_id IN ( 13, 14, 15 ) AND state = 0 AND del_flag = 0 ) GROUP BY so.inventory_id ) t 优化这条sql
时间: 2024-02-20 11:00:33 浏览: 173
这条SQL语句的性能瓶颈可能在于子查询和GROUP BY操作。以下是一些优化建议:
1. 避免使用子查询,可以使用JOIN操作代替。例如:
```
SELECT so.inventory_id AS dealUserId, so.inventory_name AS handlers,
COUNT(0) AS secondNum, COUNT(DISTINCT sri.repair_item_id) AS totalCount
FROM t_sub_order a
LEFT JOIN t_order_repair_item so ON so.sub_order_id = a.sub_order_id
LEFT JOIN t_order_repair_item sri ON sri.inventory_id = so.inventory_id
JOIN t_sls_name sn ON a.sls_name = sn.sls_name
WHERE a.repair_repeat = 1
AND so.inventory_id IS NOT NULL
AND sn.sls_model_id IN (13, 14, 15)
AND sn.state = 0 AND sn.del_flag = 0
GROUP BY so.inventory_id, so.inventory_name;
```
2. 尽量避免使用函数,例如COUNT(0)可以写成COUNT(*),可以提高性能。
3. 考虑创建适当的索引以加快查询速度。在这种情况下,可以考虑创建以下索引:
```
t_sub_order(repair_repeat, sls_name)
t_order_repair_item(sub_order_id, inventory_id)
t_order_repair_item(inventory_id)
t_sls_name(sls_name, sls_model_id, state, del_flag)
```
通过这些优化,应该能够提高查询性能。
阅读全文