Mysql SELECT 里面的 UPDATE

发布于 2024-08-16 03:54:58 字数 257 浏览 3 评论 0原文

UPDATE forms SET

pos = (SELECT MIN(pos)-1 FROM forms)

WHERE id=$id

这不起作用,错误消息:

**You can't specify target table 'form' for update in FROM clause**

我希望很清楚:我想从同一个表中获取最小的 element-1 并将其分配给 pos

UPDATE forms SET

pos = (SELECT MIN(pos)-1 FROM forms)

WHERE id=$id

This doesn't work, error message:

**You can't specify target table 'form' for update in FROM clause**

I hope it's clear: I want to get the minimal element-1 from the same table and assign it to pos

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

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

发布评论

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

评论(4

夜雨飘雪 2024-08-23 03:54:58

Consp 是对的,它不受支持。不过,有一个解决方法:

UPDATE forms SET
pos = (SELECT MIN(pos)-1 FROM (SELECT * FROM forms) AS x)
WHERE id=$id

一个可能更快的版本:

UPDATE forms 
SET pos = (SELECT pos-1 FROM (SELECT MIN(pos) AS pos FROM forms) AS x)
where id=$id

Consp is right that it's not supported. There's a workaround, however:

UPDATE forms SET
pos = (SELECT MIN(pos)-1 FROM (SELECT * FROM forms) AS x)
WHERE id=$id

A version that is probably faster:

UPDATE forms 
SET pos = (SELECT pos-1 FROM (SELECT MIN(pos) AS pos FROM forms) AS x)
where id=$id
情定在深秋 2024-08-23 03:54:58

您的问题在 MySQL 手册中已明确说明

目前,您无法更新表并在子查询中从同一个表中进行选择。

您将需要使用交易。关闭自动提交,开始事务,然后执行 SELECT MIN(pos)-1 FROM forms FOR UPDATE,获取该结果,用它进行更新,然后提交事务。

Your problem is stated plainly in the MySQL manual:

Currently, you cannot update a table and select from the same table in a subquery.

You'll want to use a transaction. Turn AutoCommit off, begin a transaction, then do a SELECT MIN(pos)-1 FROM forms FOR UPDATE, take that result, do the update with it, then commit your transaction.

陌伤ぢ 2024-08-23 03:54:58

您还可以尝试:

START TRANSACTION;
SET @newMin := MIN(pos)-1 FROM forms;
UPDATE forms SET pos=@newMin WHERE id='$id';
COMMIT;

You could also try:

START TRANSACTION;
SET @newMin := MIN(pos)-1 FROM forms;
UPDATE forms SET pos=@newMin WHERE id='$id';
COMMIT;
友谊不毕业 2024-08-23 03:54:58

我认为您不能在更新语句中使用子查询,但无论如何都有解决方法......

这是来自以下站点的引用:

"dev.mysql.com"

“目前,您不能在子查询中从表中删除并从同一个表中进行选择”

I think that you can not use a subquery inside an update statement, but any way there are workarounds for it ...

Here is a Quotation from the following site:

"dev.mysql.com"

“Currently, you cannot delete from a table and select from the same table in a sub-query ”

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