How can I speed up MySQL query with multiple joins

前端 未结 7 1640
再見小時候
再見小時候 2021-02-07 11:25

Here is my issue, I am selecting and doing multiple joins to get the correct items...it pulls in a fair amount of rows, above 100,000. This query takes more than 5mins when the

7条回答
  •  没有蜡笔的小新
    2021-02-07 12:22

    Well, first, make a subquery to decimate table1 down to just the records you actually want to go to all the trouble of joining...

    SELECT DISTINCT t1.first_name, t1.last_name, t1.email  
    FROM (  
    SELECT first_name, last_name, email, CU_id FROM table1 WHERE  
    table1.subscribe = 1  
    AND table1.Cdate >= $startDate  
    AND table1.Cdate <= $endDate  
    ) AS t1  
    INNER JOIN table2 AS t2 ON t1.CU_id = t2.O_cid  
    INNER JOIN table3 AS t3 ON t2.O_ref = t3.I_oref  
    INNER JOIN table4 AS t4 ON t3.I_pid = t4.P_id  
    INNER JOIN table5 AS t5 ON t4.P_cat = t5.C_id  
    WHERE t5.store = 2
    

    Then start looking at modifying the directionality of the joins.

    Additionally, if t5.store is only very rarely 2, then flip this idea around: construct the t5 subquery, then join it back and back and back.

提交回复
热议问题