简体   繁体   中英

MySQL RDS Stored Procedure Update query is slow

I have an update query in the Stored Procedure that updates TABLE1 based on the IDs present from TABLE2. This is written using a subquery as follows.

update TABLE1 A
set status = 'ABC'
where A.ID in (
        select ID
        from TABLE2 B
        where B.SE_ID = V_ID
            and B.LOAD_DT = V_DT
        );

I have rewritten this using,

  • a JOIN

  • masking the subquery from the main query

  • Used a temp table and join.

Standalone update is faster.

But placing this in the Stored Procedure is very slow. TABLE1 needs to be updated with 2000 records from the 2000 ID from TABLE2.

Someone please help on this.

Avoid using subqueries in place of joins. MySQL optimizes this use of subquery very poorly. That is, it may run the subquery up to 2000 times.

Use a join:

UPDATE TABLE1 A
INNER JOIN TABLE2 B
  ON A.ID = B.ID
SET A.status = 'ABC'
WHERE B.SE_ID = V_ID
  AND B.LOAD_DT = V_DT;

You'll want to create an index to optimize this.

ALTER TABLE TABLE2 ADD INDEX (SE_ID, LOAD_DT, ID);

No need to create an index on TABLE1, if my assumption is correct that its ID column is its primary key. That is itself an index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM