Select query with three where conditions is slow, but the same query with any combination of two of the three where conditions is fast

前端 未结 3 1331
暖寄归人
暖寄归人 2021-01-03 08:33

I have the following query:

SELECT table_1.id

FROM
table_1
LEFT JOIN table_2 ON (table_1.id = table_2.id)

WHERE
table_1.col_condition_1 = 0
AND table_1.col         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 09:31

    Try to split the existing SQL in two parts and see what are the execution times for each. This would hopefully give you what part is responsible for the slowness:

    part 1:

    SELECT table_1.id
      FROM table_1
      LEFT JOIN table_2
        ON (table_1.id = table_2.id)
     WHERE table_1.col_condition_1 = 0
       AND table_1.col_condition_2 NOT IN (3, 4)
       AND table_2.id is NULL
    

    and part 2 (note the inner join here):

    SELECT table_1.id
      FROM table_1
      JOIN table_2
        ON (table_1.id = table_2.id)
     WHERE table_1.col_condition_1 = 0
       AND table_1.col_condition_2 NOT IN (3, 4)
       AND table_1.date_col > table_2.date_col
    

    I expect the part 2 would be the one to take longer. In this I think an index on both table_1 and table_2 on date_coll would help.

    I don't think the composite index would help at all in your select.

    This said it is hard to diagnose why the three conditions together would impact the performance that badly. It seems to be related to your data distribution. Not sure about mySql but in Oracle a statistics collections on those tables would make a difference.

    Hope it helps.

提交回复
热议问题