开发者

Updating a mysql-table. one field = old_value - 1

开发者 https://www.devze.com 2023-02-21 14:04 出处:网络
Wh开发者_运维百科at I need to do is: - Delete one entry from table formfields - Update EVERY field with ordering > (ordering of the deleted field)

Wh开发者_运维百科at I need to do is: - Delete one entry from table formfields - Update EVERY field with ordering > (ordering of the deleted field) - Set the ordering of the updated fields to the current value minus 1 (e.g. if current ordering on the field is 8, then it should be set to 7).

Is that possible in one query? Or how can I make it happen?


You can set up a transaction to do this all at once.

Given the following table:

CREATE TABLE `formfields` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) NOT NULL,
  `order_no` int(11) NOT NULL,
  PRIMARY KEY (`id`)
);

You can do something like the following:

START TRANSACTION;
DELETE FROM formfields WHERE order_no = {YOUR_NUM};
UPDATE formfields SET order_no = order_no - 1 WHERE order_no > {YOUR_NUM};
COMMIT;


You obviously can't do the DELETE and the UPDATE in the same query, but you could use InnoDB, start a transaction, run the delete query and then use an update query such as...

UPDATE formfields SET field_value = field_value - 1 
WHERE field_value >= <VALUE YOU'VE JUST DELETED>

...prior to committing the transaction.

Doing the two queries back to back using a MyISAM table will work nine times out of ten (depending on load, etc.), but you really shouldn't go there.

0

精彩评论

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