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.). This way the ON
statement is done without any index, which is slow.
You should create a query on which you join tblB on tblA, and do your group_concat on the result of both.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.