2014-02-20 114 views
0

我有一个左连接:MySQL的左连接很慢

$query = "SELECT a.`id`, a.`documenttitle`, a.`committee`, a.`issuedate`, b.`tagname` 
    FROM `#__document_management_documents` AS a 
    LEFT JOIN `#__document_managment_tags` AS b 
    ON a.id = b.documentid 
    ".$tagexplode." 
    ".$issueDateText." 
    AND a.committee in (".$committeeQueryTextExplode.") 
    AND a.documenttitle LIKE '".$documentNameFilter."%' 
    GROUP BY a.id ORDER BY a.documenttitle ASC 

    "; 

这真是慢abaout7秒在4000个记录

任何想法我可能是做错了

SELECT a.`id`, a.`documenttitle`, a.`committee`, a.`issuedate`, b.`tagname` 
FROM `w4c_document_management_documents` AS a 
LEFT JOIN `document_managment_tags` AS b 
ON a.id = b.documentid WHERE a.issuedate >= '' 
AND a.committee in ('1','8','9','10','11','12','13','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47') 
AND a.documenttitle LIKE '%' GROUP BY a.id ORDER BY a.documenttitle ASC 
+1

可以在插入PHP值后显示查询吗? –

+0

如果您在表a中有很多记录,它可能是where子句中的运算符放慢了速度。考虑使用全文索引并匹配(...)() – markg

+0

您可以执行并显示以下结果:'SHOW INDEX FROM __document_management_documents; SHOW INDEX FROM __document_managment_tags;' – kmas

回答

0

我会在a.committee上放一个索引,全文索引在doctitle col上。 IN和LIKE是我的直接标志。发行日期也应该有一个指标,因为你是> =它

0

尝试在MySQL客户端运行以下命令:

show index from #__document_management_documents; 
show index from #_document_management_tags; 

检查,看是否有键/从iddocumentid领域指标各自的表格。如果没有,MySQL将进行全表扫描来查找值。在这些字段上创建索引使搜索时间成为对数,因为它将它们排序存储在索引文件中的二叉树中。更好的办法是使用主键(如果可能的话),因为这样行数据就存储在叶中,从而节省了MySQL的另一个I/O操作来查找数据。

也可能只是IN和> =运算符的性能很差,在这种情况下,您可能需要重新编写查询或重新设计表格。

0

如上所述,尝试查找您的列是否有索引。您甚至可以在查询开始时在您的MySQL客户端执行“EXPLAIN”命令,查看查询是否实际使用索引。您将在“关键”栏和“额外”栏中看到。获取更多信息here

这将帮助您优化您的查询。另外按原因使用临时和filesort,这会导致MySQL创建一个临时表并遍历每一行。如果你可以使用PHP来分组将会更快。