select lot_id, max(claim_time)claim_time, count(case when(ope_category='Ship')then lot_id else null end) as LS, count(case when(ope_category='Unship') then lot_id else null end) as LUS from f3rpt.F3_TB_DAILY_FABOUT where substr(lot_id,1,2) not in('CA','CW','ES','E0','EM') and lot_type = 'Production' AND LOT_ID NOT LIKE 'H%' and substr(lot_id,7,4)='.00F' and ope_category in ('Ship','Unship') and year(claim_time) = year(current date - 1 days) and month(claim_time) = month(current date - 1 days) group by lot_id) as a where LS - LUS > 0 ,以上sql如何优化
时间: 2024-02-14 20:10:09 浏览: 143
这个SQL语句中,可以优化的地方如下:
1. 在WHERE子句中,使用函数year()和month()可能导致索引失效,可以考虑将其改为claim_time的范围查询,如下所示:
```
AND claim_time >= DATE(current date - 1 month) AND claim_time < DATE(current date)
```
2. 在COUNT函数中,使用CASE语句进行条件统计,可以改为使用SUM函数,如下所示:
```
SUM(CASE WHEN ope_category='Ship' THEN 1 ELSE 0 END) AS LS
SUM(CASE WHEN ope_category='Unship' THEN 1 ELSE 0 END) AS LUS
```
3. 在WHERE子句中,使用了聚合函数,将查询结果限制在LS-LUS>0的记录,这种方式不利于索引的使用,可以考虑使用HAVING子句,如下所示:
```
HAVING LS > LUS
```
4. 在子查询中,只需要查询claim_time的最大值,可以使用MAX函数来代替ORDER BY和LIMIT 1子句,如下所示:
```
MAX(claim_time) AS claim_time
```
综上所述,优化后的SQL语句如下:
```
SELECT lot_id, MAX(claim_time) AS claim_time,
SUM(CASE WHEN ope_category='Ship' THEN 1 ELSE 0 END) AS LS,
SUM(CASE WHEN ope_category='Unship' THEN 1 ELSE 0 END) AS LUS
FROM f3rpt.F3_TB_DAILY_FABOUT
WHERE substr(lot_id,1,2) NOT IN ('CA','CW','ES','E0','EM')
AND lot_type = 'Production'
AND LOT_ID NOT LIKE 'H%'
AND substr(lot_id,7,4)='.00F'
AND ope_category IN ('Ship','Unship')
AND claim_time >= DATE(current date - 1 month) AND claim_time < DATE(current date)
GROUP BY lot_id
HAVING LS > LUS;
```
阅读全文