mysql stored procedure is slower 20 times than standard query

前端 未结 4 369
梦谈多话
梦谈多话 2020-12-16 13:33

i have 10 tables with same structure except table name.

i have a sp (stored procedure) defined as following:

 select * from table1 where (@param1 IS          


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 14:07

    Just a guess:

    When you run the query by hand, the expression WHERE ('test' IS NULL or COL1 = 'test') can be optimized when the query is being parsed. The parser can see that the string 'test' is not null, so it converts the test to WHERE COL1 = 'test'. And if there's an index on COL1 this will be used.

    However, when you create a stored procedure, parsing occurs when the procedure is created. At that time, it doesn't know what @param will be, and has to implement the query as a sequential scan of the table.

    Try changing your procedure to:

    IF @param IS NULL
    THEN BEGIN
      SELECT * FROM table1
      UNION ALL
      SELECT * FROM table2
      ...
    END;
    ELSE BEGIN
      SELECT * FROM table1 WHERE col1 = @param
      UNION ALL
      SELECT * FROM table2 WHERE col1 = @param
      ...
    END;
    END IF;
    

    I don't have much experience with MySQL stored procedures, so I'm not sure that's all the right syntax.

提交回复
热议问题