简体   繁体   中英

Update internal list indexes on many side of a one to many relationship

I have a table that has some data corruption.

The table has the many side of the one to many relationship, eg order and orderItem.

The order items are in a list, and the code keeps them ordered using an index. The index gets out of order sometimes, so instead of index entries being 0, 1, 2, 3, etc, it is 0, 3, 4, 4, or 1, 2, 3, 4, 5, etc.

I have a query that identifies the orders where this occurs, but now want to be able

I am using MySQL 5.077.

This link has a solution for a different database, but not sure how to adopt to MySQL. http://haacked.com/archive/2004/02/28/sql-auto-increment.aspx

any tips appreciated.

how about this:

SET @RowCount = -1;

UPDATE <table>
SET    <index> = (@RowCount := @RowCount + 1)
WHERE  ...
ORDER BY ...;

If you need to reassign the indices in a specific order, you can use ORDER BY. I didn't think this would work, but it works for me.

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