MySQL Query IN() Clause Slow on Indexed Column

前端 未结 5 459
自闭症患者
自闭症患者 2020-12-03 01:18

I Have a MySQL query that is being generated by a PHP script, the query will look something like this:

SELECT * FROM Recipe_Data WHERE 404_Without_200 = 0 A         


        
5条回答
  •  臣服心动
    2020-12-03 01:53

    The problem is that IN is basically treated as a bunch of ORs (e.g.

    col IN (1,2,3)
    

    is

    col = 1 OR col = 2 OR col = 3
    

    This is a LOT slower than a join.

    What you should do is to generate the SQL code which creates the temporary table, populates it with the values in the "IN" clause, and then join with that temp table

    CREATE TEMPORARY TABLE numbers (n INT)
    

    Then in a loop, add

    INSERT numbers  VALUES ($next_number)
    

    Then at the end

    SELECT * FROM numbers, Recipe_Data 
    WHERE numbers.n = RHD_No
    

提交回复
热议问题