为什么两个相同的MySQL问题有不同的执行计划并且需要花费大量不同的时间?

时间:2017-12-06 02:10:04

标签: mysql

我有两个基本相同的陈述。然而,一个需要55秒,另外2秒。为什么?

以下是可以正常运行的查询:

SELECT
    employees.EmployeeID
FROM
    employees
LEFT JOIN req_budget_centers ON employees.BudgetCenter =    req_budget_centers.BudgetCenter
INNER JOIN req_bcjc ON employees.BudgetCenter = req_bcjc.BudgetCenter AND   employees.JobCode = req_bcjc.JobCode AND employees.EmpContr = req_bcjc.EmpContr
INNER JOIN j_bcjc_req ON req_bcjc.bcjcID = j_bcjc_req.bcjcID
INNER JOIN req_requirements ON j_bcjc_req.requirementID =   req_requirements.id
WHERE
    req_requirements.BoardCategoryID = 4 /*PROBLEM VALUE*/
    AND req_requirements.isActive = 1
    AND employees.`Status` = 'A'

以下是需要50多秒的查询代码:

SELECT
    employees.EmployeeID
FROM
    employees
LEFT JOIN req_budget_centers ON employees.BudgetCenter =    req_budget_centers.BudgetCenter
INNER JOIN req_bcjc ON employees.BudgetCenter = req_bcjc.BudgetCenter AND   employees.JobCode = req_bcjc.JobCode AND employees.EmpContr = req_bcjc.EmpContr
INNER JOIN j_bcjc_req ON req_bcjc.bcjcID = j_bcjc_req.bcjcID
INNER JOIN req_requirements ON j_bcjc_req.requirementID =   req_requirements.id
WHERE
    req_requirements.BoardCategoryID = 8 /* WORKS FINE */
    AND req_requirements.isActive = 1
    AND employees.`Status` = 'A'

以下是这两个查询的执行计划: enter image description here

数据库或表中没有任何内容与8和4的值不同......所涉及的总记录数相同......我如何在这里找到瓶颈?

我还要补充一点,将条件(= 8或= 4)完全取消,但保留所有连接,也会大大加快查询速度......

1 个答案:

答案 0 :(得分:-1)

我建议传递参数并检查值4和8的时间。

示例:如何传递参数。设置@type ='foo';

从Stuff中选择*类型= @ type;