MySQL优化:select brandName,have_vin_count,(select count(1) from epc_carmodel_skucount where ifnull(vin,'') <> '') as have_vin_sum_count, concat(round(have_vin_count/(select count(1) from epc_carmodel_skucount where ifnull(vin,'') <> '')*100, 2),'%') as have_vin_percent from (select b.brandName,count(distinct a.vehicleUUID) as have_vin_count from (select distinct vehicleUUID from epc_carmodel_skucount where ifnull(vin,'') <> '') a inner join ( select b.brandName,b.vehicleUUID from epc_material_sence_model a join ( select * from epc_bom_sence where brandName not in ('演示','测试','客服内测') and ifnull(brandName,'') <> '' and brandName not like '火星%' and brandName not like '原厂%' ) b on a.oeId=b.oeId where a.categoryName='火花塞' ) b on a.vehicleUUID=b.vehicleUUID group by b.brandName
时间: 2023-12-19 17:07:20 浏览: 123
这段 SQL 语句是查询汽车品牌的火花塞车型中,有 VIN 码的车型数量及占比。其中使用了子查询和连接查询,可能会有性能问题。建议优化如下:
1. 尽量避免在子查询中使用聚合函数,可以将子查询的结果存储到临时表中,以提高查询效率。
2. 将子查询中的 ifnull(vin,'') <> '' 转换为 vin IS NOT NULL AND vin <> '',可以利用索引优化查询。
3. 使用 JOIN 操作时,尽量通过 ON 子句指定连接条件,避免使用 WHERE 子句进行过滤,提高查询效率。
优化后的 SQL 语句如下:
```
SELECT
b.brandName,
COUNT(DISTINCT a.vehicleUUID) AS have_vin_count,
COUNT(DISTINCT c.vehicleUUID) AS have_vin_sum_count,
CONCAT(ROUND(COUNT(DISTINCT a.vehicleUUID) / COUNT(DISTINCT c.vehicleUUID) * 100, 2), '%') AS have_vin_percent
FROM
epc_carmodel_skucount a
INNER JOIN (
SELECT
b.brandName,
b.vehicleUUID
FROM
epc_material_sence_model a
JOIN (
SELECT *
FROM epc_bom_sence
WHERE brandName NOT IN ('演示', '测试', '客服内测')
AND IFNULL(brandName, '') <> ''
AND brandName NOT LIKE '火星%'
AND brandName NOT LIKE '原厂%'
) b
ON a.oeId = b.oeId
WHERE a.categoryName = '火花塞'
) b
ON a.vehicleUUID = b.vehicleUUID
AND a.vin IS NOT NULL
AND a.vin <> ''
LEFT JOIN epc_carmodel_skucount c
ON c.vin IS NOT NULL
AND c.vin <> ''
GROUP BY
b.brandName
```
这样,可以避免子查询中的聚合函数,使用 INNER JOIN 操作指定连接条件,同时使用 LEFT JOIN 操作获取所有有 VIN 码的车型数量,从而提高查询效率。
阅读全文