简体   繁体   中英

MySQL update an AUTO_INCREMENT pk to preserve row ordering

I have a table with three columns: id , foreign_id , and tag . Queries on this table are ordered first by foreign_id , then by tag , but we want to deprecate the tag column in favor of the more reliable and auto-generated id . In doing so, we also need to preserve the ordering data stored in the tag column without keeping tag around. This ordering only makes sense within the scope of the foreign_id column.

To solve this problem, we've decided to update the id s within the scope of each foreign_id such that the order of the ids preserves the tag order information.

How does one update an AUTO_INCREMENT primary key column such that it gets assigned the next value in the counter without changing the rest of the row?

Alternatively, how would one copy an entire row (minus the pk) into a new row and delete the old row?

SELECT MAX(id) INTO @maxID FROM the_table;
UPDATE the_table SET id = id + @maxID;
SET @i := 0;
UPDATE the_table SET id = (@i := @i + 1) ORDER BY foreign_id, tag;

I am not 100% positive this will work; I don't usually do this kind of things with UPDATE statements. Alternatively, you could replace that last UPDATE with:

INSERT INTO the_table(id, foreign_id, tag) 
SELECT (@i := @i + 1) AS `new_id`, foreign_id, tag 
FROM the_table 
ORDER BY foreign_id, tag
;
DELETE FROM the_table 
WHERE id >= @maxID
;

In either case, this assumes current id values are always >= 0.

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