简体   繁体   中英

MySQL - Update table with min date from another table

I have a table ( table1 ) containing a user ID and transaction dates ( stt_stid , stt_date ) as well as some other non-relevant info.

I have another table ( table2 ) with a couple hundred records that I need to get the min(stt_date) for based on table1.stt_stid = table2.stid .

table1 is 5M + rows and I'm having trouble writing an efficient join without getting an error.

I've tried something along the lines of:

UPDATE table2 JOIN (
    SELECT stt_stid,
           MIN(stt_date) AS mindate
      FROM table1
     WHERE stt_amt > 0
       AND stt_prid = 1
     GROUP BY stt_stid) temp
    ON table2.stid = table1.stt_stid
 SET table2.firstdate = temp.mindate

If that inline view query is supposed to be referencing table1 , make sure you have an index defined

ON table1 (stt_stid, stt_date)

That will allow MySQL to make use of an index to satisfy the query. If MySQL can't use an index to satisfy the GROUP BY and get the minimum value, then that's going to require a "Using filesort" operation, on all the rows in table1 , and that's expensive for large sets. (MySQL can make use of a suitable index to avoid that operation.)

The result from that inline view query is going to materialized as a "derived table", and then the outer query will run. Before MySQL 5.6, there won't be any index on the "derived table".

(I'm assuming that nearly every stid value in table1 also appears in table2 , that is, that table2 doesn't contain a very small subset of stid values... if that's not the case, the moving a JOIN into the derived table may significantly reduce the size of the derived table.)

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