简体   繁体   English

在MySQL中使用max和where子句与子查询进行内部联接

[英]INNER JOIN with subquery with max and where clause in mysql

SELECT a.ts, b.barcodenumber, a.remarks, c.department 
FROM documentlog a 
INNER JOIN (select docid, max(logid) as logid from documentlog GROUP BY docid) d ON d.docid=a.docid AND d.logid=a.logid 
INNER JOIN user c ON c.uid=a.user 
INNER JOIN document b ON b.id=a.docid
WHERE c.department = 'PTO' AND b.end = 0

My problem is When I execute this query it's slow like 2sec+ execution but the data is only 9 , How can I speed up the execution of my query? 我的问题是,当我执行此查询时,它的执行速度像2秒以上,但数据仅为9秒,如何才能加快查询的执行速度?

Old SS for EXPLAIN RESULT 旧SS的解释结果

UPDATED SS for EXPLAIN RESULT (Add INDEX logid,docid) 已更新SS以获取解释结果(添加INDEX logid,docid)

Check out your EXPLAIN result. 查看您的EXPLAIN结果。 Notice that MySQL does not use any kind of key when querying the documentlog table ie, the documentlog table does not have a key defined on it. 注意,在查询documentlog日志表时,MySQL不使用任何类型的键,即documentlog日志表上没有定义键。 More than 2 million records are processed at this point in your query. 此时,您的查询中已处理了超过200万条记录。 This could be the most likely source of the slowness of your query. 这可能是查询缓慢的最可能原因。

Add an index on the docid , and logid fields in your documentlog table and check if it improves the queries' execution time. documentlog表的docidlogid字段上添加索引,并检查它是否可以缩短查询的执行时间。

Update!! 更新!!

The output of the updated EXPLAIN query is saying that it is using a full table scan!! 更新的EXPLAIN查询的输出表明它正在使用全表扫描! (ie, type=ALL ) to produce the output of the main outer query. (即type=ALL )生成主要外部查询的输出。 Why? 为什么? This is caused by the fact that there are no indices defined on the attributes used in the Where clause ie, ( department and end ). 这是由于在Where子句中使用的属性(即( departmentend )上没有定义索引)引起的。

In general, if you want to speed up queries, then one has to make sure that appropriate indices are defined for the attributes used in the queries' WHERE condition. 通常,如果要加快查询速度,则必须确保为查询的WHERE条件中使用的属性定义了适当的索引。

By the way, you can learn more about the meaning of MySQL's EXPLAIN result by reading its documentation . 顺便说一句,您可以通过阅读MySQL 文档了解有关MySQL EXPLAIN结果含义的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM