SELECT `employee_name` FROM `ent_user_relation` WHERE `ent_code` = 'EC2108032181SXBL' and `user_code` IN ( SELECT DISTINCT (`user_code`) FROM `license_user` WHERE `ent_code` = 'EC2108032181SXBL' and `is_deleted` = 0 and `user_code` NOT IN( ( SELECT `reim_user_code` FROM `reimburse_data` WHERE `enterprise_code` = 'EC2108032181SXBL' ) union ( SELECT `request_user_code` FROM `loan_form_data` WHERE `ent_code` = 'EC2108032181SXBL' ) ) );优化下上述代码
时间: 2024-02-15 19:10:38 浏览: 101
PyPI 官网下载 | air_drf_relation-0.0.8.tar.gz
可以考虑使用 JOIN 语句来代替子查询,这样可以使查询效率更高。以下是优化后的 SQL 语句:
```
SELECT DISTINCT `employee_name`
FROM `ent_user_relation`
JOIN `license_user` ON `ent_user_relation`.`user_code` = `license_user`.`user_code`
LEFT JOIN (
SELECT `reim_user_code` AS `user_code` FROM `reimburse_data` WHERE `enterprise_code` = 'EC2108032181SXBL'
UNION
SELECT `request_user_code` AS `user_code` FROM `loan_form_data` WHERE `ent_code` = 'EC2108032181SXBL'
) AS `excluded_users` ON `license_user`.`user_code` = `excluded_users`.`user_code`
WHERE `ent_user_relation`.`ent_code` = 'EC2108032181SXBL'
AND `license_user`.`is_deleted` = 0
AND `excluded_users`.`user_code` IS NULL;
```
该语句使用了 JOIN 语句,将子查询转换为了一个临时表。LEFT JOIN 用于左连接,将两个子查询的结果合并为一个表,并用 IS NULL 来判断是否在排除列表中。这样可以使查询效率更高。
阅读全文