简体   繁体   中英

How to optimize a query that's running too slow (LEFT JOIN)

My query is running too slow.....
any ways to speed it up?

SELECT SQL_CALC_FOUND_ROWS a.*, b.*, c.*, d.*, e.*, f1.*, st6.* 
FROM tbl_a a 
LEFT JOIN tbl_b b ON a.m_id = b.m_id 
LEFT JOIN tbl_c c ON a.ms_id = c.ms_id 
LEFT JOIN tbl_d d ON a.gd_id = d.gd_id 
LEFT JOIN tbl_e e ON a.sd_id = e.sd_id 
LEFT JOIN tbl_f f1 ON a.tp_id = f1.tp_id 
LEFT JOIN 
        (
            SELECT g.*, GROUP_CONCAT(f2.tp_name SEPARATOR ',') tp_name, f2.tp AS tp
            FROM tbl_g g
            LEFT JOIN tbl_f f2 ON g.tp_id = f2.tp_id 
            GROUP BY s_id 
        )st6 ON st6.s_id = a.s_id

Do not use LEFT unless you have a specific reason for it. I see no hint of such here.

A query like this is best optimized if it can perform the subquery first . However, 'LEFT' is a hint that it cannot be. Remove all the LEFTs and see if it is fast enough and gives the "right" answer.

Check to see that there is a PRIMARY KEY or INDEX on gd_id in both of the indicated tables in the following. (And do likewise for other JOINs.)

JOIN tbl_d d ON a.gd_id = d.gd_id

If you still need help, provide SHOW CREATE TABLE for each table. And EXPLAIN SELECT ...; .

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.

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