开发者

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 ite开发者_StackOverflow中文版ms 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜