简单查询需要很长时间(〜15秒)

时间:2018-09-24 16:37:23

标签: php mysql performance pdo time

我有以下查询和php代码:

$sql = "SELECT DISTINCT j.OrderID, DATE_FORMAT(j.StartDate,'%W %e %M %Y %H:%i:%s') AS StartDate, 
                        j.Object, j.Signature,  j.PrintedWithBSN, j.PrintedWithoutBSN,
                        p.ProjectID AS ProjectName, p.City, p.PostalCode, p.StreetName, 
                        c.Name AS CustomerName
        FROM JobOrder j
        INNER JOIN Project p ON p.ProjectID = j.ProjectID
        INNER JOIN Customer c ON c.CustomerID = p.CustomerID
        INNER JOIN OrderEmployer oe ON j.OrderID=oe.OrderID
        INNER JOIN Employer e ON oe.EmployerID=e.EmployerID
        WHERE j.Removed = 0 AND Date(j.StartDate)=:StartDate
        ORDER BY e.Firstname, p.WorkDone, j.Signature, j.StartDate DESC, c.Name";

$query = $database->prepare($sql);

$query->execute(array('StartDate' => $date));";

使用microtime php函数,我发现$query->execute大约需要15秒才能完成。一年前,查询仅在几秒钟内执行。我不知道是什么原因导致了额外的等待时间,这是我写的不好的查询吗?

-------编辑: 我的解释结果:

Explain Plan results

------- Edit2: 我的索引是(每个表):

  • 客户:主密钥:客户ID 唯一密钥:名称
  • 雇主:主密钥: EmployerID 唯一密钥:用户名
  • JobOrder:主键: OrderID 键: ProjectID
  • OrderEmployer:主密钥: OrderID,EmployerID 密钥: EmployerID
  • 项目主键:项目ID :客户ID,ContactPersonID,ContactPersonProjectID

1 个答案:

答案 0 :(得分:0)

按照Uueerdo和Barmar的提示,我修复了较长的查询时间。通过简单地向WHERE子句使用的字段添加索引,我将查询时间减少到少于0.1秒(我什至看到了0,00019192695617676秒)!