简体   繁体   English

与子查询的MySQL LEFT JOIN非常慢

[英]MySQL LEFT JOIN with SUBQUERY is very slow

In this query : 在此查询中:

SELECT tblA.id FROM tblA 
LEFT JOIN (
        SELECT invid, max(id) as maxid, group_concat(testcase) as testgrp 
        FROM tblB 
        GROUP BY invid
        ) AS tblC ON tblC.invid = tblA.id 
LEFT JOIN  tblB on tblB.id = tblC.maxid 
WHERE 1 
GROUP BY tblA.id 

subquery is fast but with left join is very slow How can I make it faster? 子查询很快,但是左联接非常慢,如何使其更快?

By doing a subquery, the result of that subquery is loaded in to memory without any reference to indexes (like primary id or foreign keys, etc.). 通过执行子查询,该子查询的结果将加载到内存中,而无需任何对索引的引用(例如主ID或外键等)。 This way the ON statement is done without any index, which is slow. 这样,在没有任何索引的情况下完成ON语句,这很慢。

You should create a query on which you join tblB on tblA, and do your group_concat on the result of both. 您应该创建一个查询,然后在tblA上加入tblB,然后对两者的结果都进行group_concat。

I'm not sure what your end result should be based on your example, so I can't provide you a query. 我不确定根据您的示例得出的最终结果应该是什么,因此无法向您提供查询。

Looking to your code you could avoid a left join 查看您的代码,您可以避免左联接

SELECT tblC.id FROM (
        SELECT tblA.id, tblB.invid, max(tblB.id) as maxid, 
              group_concat(tblB.testcase) as testgrp 
        FROM  tblB 
        left  tblB ON  tblA.id  =  tblB.invid
        GROUP BY tblA.id, , tblB.invid
        ) AS tblC 
LEFT JOIN  tblB on tblB.id = tblC.maxid 

why not without any join: 为什么不没有任何加入:

SELECT
    a.id,
    (SELECT max(b.id) FROM tblB as b WHERE b.invid = a.id) as maxid,
    (SELECT group_concat(b.testcase) FROM tblB as b WHERE b.invid = a.id) as testgrp 
FROM tblA as a
WHERE 1 

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

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