如何优化此查询以获得相同的结果,而不需要花费太长时间? NOT IN
子查询需要很长时间。
SELECT DISTINCT EmployeeId FROM employees
WHERE
status = 'Active'
&& BranchId = '2'
&& NOT EXISTS (
SELECT * FROM attendance
WHERE
employees.EmployeeId = attendance.EmployeeId
&& attendance.AttendanceDate = '2015-01-20'
)
)
SELECT EmployeeId FROM employees
WHERE
status = 'Active'
&& BranchId = '2'
&& NOT IN (
SELECT EmployeeId FROM attendance WHERE AttendanceDate='2015-01-20'
)
答案 0 :(得分:0)
以下是您的查询的另一个版本
select
distinct e.EmployeeId FROM employees e
left join attendance a on e.EmployeeId = a.EmployeeId and a.AttendanceDate = '2015-01-20'
where
e.status='Active'
and e.BranchId= '2'
and a.EmployeeId is null
您还需要在表格上应用一些索引
alter table employees add index st_br_idx(status,BranchId);
alter table AttendanceDate add index AttendanceDate_idx(AttendanceDate);
如果EmployeeId是外键,那么如果是,则无需添加索引 索引尚未存在,您可能还需要以下内容
alter table AttendanceDate add index EmployeeId_idx(EmployeeId);
如果EmployeeId
是employees
中的主键,那么它已经编入索引(如果没有并且没有编入索引),您可能还需要为其添加索引
alter table employees add index EmployeeId_idx(EmployeeId);
您可以在具有上述索引后检查原始查询
SELECT DISTINCT e.EmployeeId FROM employees e
WHERE
e.status='Active'
and e.BranchId= '2'
and NOT EXISTS (
SELECT 1 FROM
attendance a WHERE e.EmployeeId = a.EmployeeId
and a.AttendanceDate='2015-01-20'
)
分析查询使用explain select..
并查看优化器如何使用索引
以及优化程序可能扫描以检索记录的可能行数