简体   繁体   中英

What's the best way to update multiple unique rows of a table in MySQL?

I have a list of items in a MySQL table. The user is able to order these items by dragging them up and down in a HTML list. I then need to store each items position in the list.

Is it possible to do this in one MySQL call or does it have to be a seperate call for each product to set its own order ID?

A single call would look something like this:

UPDATE table_name SET `order` = order_number AND `product_id` = 'X';

Well, you could drop the whole table and then insert the new order numbers for all products. That's only two statements. This would work as long as this table only contains the "order" information and no other critical data.

You could delete all items in question, and insert them back again if no other data would be affected by that (CASCADE and similar). That would be two queries; DELETE with "WHERE product_id IN ('X', 'Y', ...)", and INSERT with updated values for each item.

A clean solution would be to do an UPDATE within a transaction, but as MySQL doesn't support deferred constraint checking, you would have a problem there if the 'order' attribute is UNIQUE.

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