How can I speed up MySQL query with multiple joins

前端 未结 7 1620
再見小時候
再見小時候 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:21

    At present, your query is returning all matching rows on table2-table5, just to establish whether t5.store = 2. If any of table2-table5 have a significantly higher row count than table1, this may be greatly increasing the number of rows processed - consequently, the following query may perform significantly better:

    SELECT DISTINCT t1.first_name, t1.last_name, t1.email 
    FROM table1 AS t1 
    WHERE t1.subscribe =1 
    AND t1.Cdate >= $startDate
    AND t1.Cdate <= $endDate
    AND EXISTS
    (SELECT NULL FROM table2 AS t2
    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 AND t5.store =2
    WHERE t1.CU_id = t2.O_cid);
    

提交回复
热议问题