Sql查询请求需要花费很长时间与内部联接进行特殊选择

时间:2015-05-26 10:52:25

标签: mysql sql

我应该执行一个只使用一个表的简单查询。

执行结果不是假的 - 但需要很长时间。

SELECT SUM(montantCommande) as total 
    FROM export_commandes 
    INNER JOIN (SELECT ID FROM export_adherent) AS table_adherent
    WHERE export_commandes.client_id=table_adherent.ID

2 个答案:

答案 0 :(得分:0)

以这种方式简化

SELECT SUM(montantCommande) as total 
FROM export_commandes 
INNER JOIN export_adherent AS table_adherent on export_commandes.client_id=table_adherent.ID

答案 1 :(得分:0)

这是您的查询:

SELECT SUM(montantCommande) as total 
FROM export_commandes c INNER JOIN
     (SELECT ID FROM export_adherent) a
     ON c.client_id = a.ID;

当您在MySQL中使用子查询(但在大多数其他数据库中不使用)时,它会通过实际创建派生表的努力。这不仅增加了额外的开销,而且还干扰了优化的索引。

相反,将查询短语为:

SELECT SUM(montantCommande) as total 
FROM export_commandes c INNER JOIN
     export_adherent a
     ON c.client_id = a.ID;

然后,您需要export_commands(client_id)export_adherent(id)上的索引(只会使用一个,但目前还不清楚)。您可以在适当的索引中添加montantCommande作为第二个键作为进一步优化。