sql优化:explain select pp.id, pp.lot_id, pp.lot_no, pp.measurement, pp.is_long_rent, pp.rent_license_plate, pp.rent_user, pp.rent_start_time, pp.rent_end_time, pp.create_time, pp.create_by, pp.update_time, pp.update_by, pp.is_deleted, pp.per_type, pp.space_no, CASE WHEN fo.order_no is not null AND pp.status=1 THEN 1 WHEN fo.order_no is not null AND pp.status=0 THEN 2 WHEN pp.status = 2 THEN 3 WHEN fo.order_no is null THEN 0 ELSE pp.status END as status, fo.license_plate from par_per pp left join fd_ord fo on pp.space_no = fo.space_no and fo.status = 0 and (pp.status = 0 or pp.status = 1) where pp.lot_id in (select pl.id from par_lot pl inner join sys_user_par sup on pl.id = sup.parking_id and sup.user_id = 1) AND (pp.status = 0 or pp.status = 1) AND pp.is_deleted = 0 group by pp.space_no order by status desc
时间: 2024-02-14 13:26:27 浏览: 215
为了优化这个 SQL 查询,我们可以做以下几点改进:
1. 索引优化:确保 `par_per` 表和 `par_lot` 表的相关字段上都有合适的索引,例如 `par_per.lot_id`、`par_per.space_no`、`par_per.status`、`par_per.is_deleted`,以及 `par_lot.id` 和 `sys_user_par.parking_id`。
2. 子查询优化:将子查询改为连接查询,这样可以避免在 `IN` 子查询中使用子查询。
3. 连接条件优化:在 `left join fd_ord fo` 子句中,添加条件 `fo.status = 0` 和 `(pp.status = 0 or pp.status = 1)`,以过滤不必要的行。
4. 聚合优化:根据查询需求,确定是否需要对 `pp.space_no` 进行分组和聚合。
改进后的 SQL 查询如下所示:
```sql
SELECT pp.id,
pp.lot_id,
pp.lot_no,
pp.measurement,
pp.is_long_rent,
pp.rent_license_plate,
pp.rent_user,
pp.rent_start_time,
pp.rent_end_time,
pp.create_time,
pp.create_by,
pp.update_time,
pp.update_by,
pp.is_deleted,
pp.per_type,
pp.space_no,
CASE
WHEN fo.order_no IS NOT NULL AND pp.status=1 THEN 1
WHEN fo.order_no IS NOT NULL AND pp.status=0 THEN 2
WHEN pp.status = 2 THEN 3
WHEN fo.order_no IS NULL THEN 0
ELSE pp.status
END AS status,
fo.license_plate
FROM par_per pp
LEFT JOIN fd_ord fo ON pp.space_no = fo.space_no
AND fo.status = 0
AND (pp.status = 0 OR pp.status = 1)
JOIN par_lot pl ON pp.lot_id = pl.id
JOIN sys_user_par sup ON pl.id = sup.parking_id AND sup.user_id = 1
WHERE pp.is_deleted = 0
AND (pp.status = 0 OR pp.status = 1)
GROUP BY pp.space_no
ORDER BY status DESC;
```
请注意,这只是一种可能的优化方法,具体的优化策略可能需要根据数据库的实际情况和性能测试结果进行调整。
阅读全文