已知 accountnumber 上有索引,sale20230525tmp为临时表 这段 sql 可以怎么优化 delete FROM ddm_raw_data_b2b20230525 drdb WHERE EXISTS( SELECT 1 FROM ( SELECT B.min_d, B.max_d, account.accountId FROM ( SELECT channel_erpno,max(saleto_date) as max_d,min(saleto_date) as min_d FROM sale20230525tmp GROUP BY channel_erpno) AS B LEFT JOIN account ON B.channel_erpno = account.accountnumber ) AS A WHERE A.accountId = drdb.from_accountid AND drdb.saleto_date :: date >= A.min_d :: date AND drdb.saleto_date :: date <=a.max_d :: date );
时间: 2024-02-03 10:02:22 浏览: 69
sql学习 回表是索引优化的要点之一.sql
可以尝试以下几个优化方式:
1. 将子查询中的 SELECT 1 改为 SELECT NULL,这样可以少一步查询。
2. 使用 INNER JOIN 代替 EXISTS 子查询,因为 EXISTS 子查询会在每个行上执行,而 INNER JOIN 可以在一开始执行。
3. 将子查询中的日期强制转换移至外面的 WHERE 子句中,以避免在子查询中对每个行都执行日期转换操作。
4. 对 accountnumber 和 saleto_date 字段创建索引,这样查询会更快速。
修改后的 SQL 语句如下所示:
```
DELETE FROM ddm_raw_data_b2b20230525 drdb
WHERE drdb.from_accountid IN (
SELECT A.accountId
FROM (
SELECT B.channel_erpno, MAX(saleto_date) AS max_d, MIN(saleto_date) AS min_d
FROM sale20230525tmp
GROUP BY channel_erpno
) AS B
INNER JOIN account ON B.channel_erpno = account.accountnumber
INNER JOIN (
SELECT saleto_date,
accountid,
MIN(saleto_date) OVER (PARTITION BY accountid) AS min_date,
MAX(saleto_date) OVER (PARTITION BY accountid) AS max_date
FROM ddm_raw_data_b2b20230525
) AS C ON C.accountid = account.accountid
WHERE drdb.saleto_date::date >= C.min_date::date
AND drdb.saleto_date::date <= C.max_date::date
);
```
注意:以上优化仅供参考,需要根据具体情况进行测试和调整。
阅读全文