SELECT AWB_ID,HAWB_NO,TADDRESS FROM AWB WHERE TRANS_ID IN (SELECT COMP_ID FROM COMPANY WHERE COMP_CODE IN('FEDJ','FPAK')) AND AGENT_ID in(select comp_id from company where BILLSEVERTYPE=1) and ARR_DATE>'2023-05-01' and isnull(REGION,'')='Y' and PAY_SET='Y' and isnull(TADDRESS,'')!='' and (select count(*) from REMARK where awb_id=awb.AWB_ID and REMARK like '%修改出货服务商%' and CONVERT(char(10),GETDATE(),120)=CONVERT(char(10),MODI_DATE,120))>=1 语句优化
时间: 2023-08-13 11:02:19 浏览: 77
SQL 的 SELECT 语句优化
可以尝试以下优化方法:
1. 使用JOIN代替IN和子查询
```
SELECT AWB.AWB_ID, AWB.HAWB_NO, AWB.TADDRESS
FROM AWB
JOIN COMPANY ON AWB.TRANS_ID = COMPANY.COMP_ID
JOIN COMPANY AS AGENT ON AWB.AGENT_ID = AGENT.COMP_ID
LEFT JOIN REMARK ON AWB.AWB_ID = REMARK.AWB_ID
WHERE COMPANY.COMP_CODE IN ('FEDJ', 'FPAK')
AND AGENT.BILLSEVERTYPE = 1
AND AWB.ARR_DATE > '2023-05-01'
AND ISNULL(AWB.REGION, '') = 'Y'
AND AWB.PAY_SET = 'Y'
AND ISNULL(AWB.TADDRESS, '') != ''
AND REMARK.REMARK LIKE '%修改出货服务商%'
AND CONVERT(char(10), GETDATE(), 120) = CONVERT(char(10), REMARK.MODI_DATE, 120)
```
2. 使用索引
为了使查询更快,可以在AWB表上创建以下联合索引:
```
CREATE INDEX idx_AWB ON AWB (TRANS_ID, AGENT_ID, ARR_DATE, REGION, PAY_SET, TADDRESS)
```
为了支持LEFT JOIN REMARK,可以在REMARK表上创建以下索引:
```
CREATE INDEX idx_REMARK ON REMARK (AWB_ID, REMARK, MODI_DATE)
```
3. 避免使用函数
在WHERE子句中使用函数会影响查询性能。如果可能的话,可以将查询条件中的函数转换为变量或常量。
例如,将以下条件:
```
CONVERT(char(10), GETDATE(), 120) = CONVERT(char(10), REMARK.MODI_DATE, 120)
```
转换为:
```
@today = CONVERT(char(10), GETDATE(), 120)
...
AND @today = CONVERT(char(10), REMARK.MODI_DATE, 120)
```
阅读全文