更新 mysql 表。一个字段 = old_value - 1

发布于 2024-10-29 12:37:18 字数 161 浏览 4 评论 0原文

我需要做的是: - 从表 formfields 中删除一项 - 使用排序更新每个字段> (删除字段的排序) - 将更新字段的排序设置为当前值减 1(例如,如果字段的当前排序为 8,则应将其设置为 7)。

这可以在一个查询中实现吗?或者我怎样才能让它发生?

What 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不弃不离 2024-11-05 12:37:18

您可以设置一个交易来一次性完成这一切。

给出下表:

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

您可以执行如下操作:

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 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;
鸩远一方 2024-11-05 12:37:18

显然你不能在同一个查询中执行DELETEUPDATE,但是你可以使用InnoDB,启动一个事务,运行删除查询,然后使用更新查询例如...

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

...在提交交易之前。

使用 MyISAM 表连续执行两个查询十有八九会起作用(取决于负载等),但您确实不应该这样做。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文