Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 不在子查询中执行时间太长_Mysql_Mysql Slow Query Log - Fatal编程技术网

Mysql 不在子查询中执行时间太长

Mysql 不在子查询中执行时间太长,mysql,mysql-slow-query-log,Mysql,Mysql Slow Query Log,我如何优化此查询以获得相同的结果,而不需要花费那么长的时间?不在子查询需要很长时间 SELECT DISTINCT EmployeeId FROM employees WHERE status = 'Active' && BranchId = '2' && NOT EXISTS ( SELECT * FROM attendance WHERE employees.EmployeeId = a

我如何优化此查询以获得相同的结果,而不需要花费那么长的时间?
不在
子查询需要很长时间

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'
    )

这是您的查询的另一个版本

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'
)
要分析查询,请使用
解释选择..
并查看优化器如何使用索引 以及优化器可能扫描以检索记录的行数