简体   繁体   中英

mysql update row with value from another row

I'm not particularly new to mysql, but I'm new to updating very large tables. I can do this while using two queries, but I'm attempting to make the process faster because I'm going to end up doing this for millions of rows. I've been trying to update a table, based on another row in the same table. The table I have looks something like:

table

Basically what I'd like to do is update the 'prev_num_dialed' field with the 'dialed_num' field of the same 'callid', but from the previous 'segment'.

so the first line callid '1', segment '1', would not update 'prev_num_dialed' because there's no previous segment. However the second line callid '1', segment '2', would update 'prev_num_dialed' to '1234567' because that's what the previous segments number was.

My current attempt looks like the following:

$query = "UPDATE " . $table_name . " as t1 
SET t1.prev_num_dialed = (
SELECT dialed_num, callid
FROM (SELECT * FROM " . $table_name . ") as t2
WHERE t2.segment = t1.segment - 1)
AND t2.callid = t1.callid
";

but this is not working as I'd like it to, it's updating from its own row. Any help on this is appreciated.

I would simply suggest:

UPDATE $table_name t1 JOIN
       $table_name t2
       ON t2.callid = t1.callid AND
          t2.segment = t1.segment - 1
    SET t1.prev_num_dialed = t2.dialed_num;

I think this does what you intend. This does not set the column value to NULL if there is no match. You can do that with a LEFT JOIN instead of a JOIN .

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