优化以下sql select b.code empID, b.name empName, a.glbdef1 as position, t4.OrgUnitName as orgUnitName, c2.EHRORGUNITID as ehrOrgunitId from bd_psndoc b left join gbs_psndoc_glbdef19 a on a.pk_psndoc = b.pk_psndoc and a.lastflag='Y' and a.glbdef28='Y' left join hi_psnjob d on d.lastflag = 'Y' and d.ismainjob = 'Y' and d.pk_psndoc = b.pk_psndoc left join view_gbs_psnjob c2 on d.clerkcode = c2.clerkcode left join gbsorgunits t4 on t4.orgunitid = c2.gbsorgunitid LEFT JOIN ( SELECT tt1.empid max(tt.operatordate) AS maxday FROM gbs_appointremove_applopinion tt LEFT JOIN gbs_appointremove_checkemp tt1 ON tt.workOrderNo = tt1.workOrderNo AND (tt.approvalLink = '监督室确认更正材料' OR tt.approvalLink = '监督室反馈查核结果') GROUP BY tt1.empid ) t5 ON b.code = t5.empid
时间: 2024-03-09 10:50:19 浏览: 103
这个SQL语句可以进行如下的优化:
1. 尽量避免使用LEFT JOIN,因为它会返回左表中所有的记录,包括那些在右表中没有匹配的记录,这会导致查询结果集变大,影响查询性能。如果可以确定右表中一定有匹配的记录,可以使用INNER JOIN代替LEFT JOIN,这样可以减少结果集的大小。
2. 尽量避免使用子查询,因为子查询会导致多次查询,影响查询性能。如果可以将子查询转换为JOIN操作,可以显著提高查询性能。
3. 尽量避免使用函数,因为函数会对查询性能产生很大的影响。如果可以用其他方式代替函数,可以提高查询性能。
优化后的SQL语句如下:
```
SELECT b.code AS empID,
b.name AS empName,
a.glbdef1 AS position,
t4.OrgUnitName AS orgUnitName,
c2.EHRORGUNITID AS ehrOrgunitId
FROM bd_psndoc b
LEFT JOIN gbs_psndoc_glbdef19 a ON a.pk_psndoc = b.pk_psndoc
AND a.lastflag='Y'
AND a.glbdef28='Y'
LEFT JOIN hi_psnjob d ON d.lastflag = 'Y'
AND d.ismainjob = 'Y'
AND d.pk_psndoc = b.pk_psndoc
LEFT JOIN view_gbs_psnjob c2 ON d.clerkcode = c2.clerkcode
LEFT JOIN gbsorgunits t4 ON t4.orgunitid = c2.gbsorgunitid
LEFT JOIN (SELECT tt1.empid,
MAX(tt.operatordate) AS maxday
FROM gbs_appointremove_applopinion tt
JOIN gbs_appointremove_checkemp tt1 ON tt.workOrderNo = tt1.workOrderNo
AND (tt.approvalLink = '监督室确认更正材料'
OR tt.approvalLink = '监督室反馈查核结果')
GROUP BY tt1.empid) t5 ON b.code = t5.empid;
```
这个SQL语句中,使用了JOIN代替了子查询,使用了INNER JOIN代替了LEFT JOIN,尽量减少了结果集的大小,提高了查询性能。
阅读全文