mysql 一个较特殊的问题:You can't specify target table 'wms_cabinet_form'

时间:2024-01-24 19:07:13 

今天在写 mysql 遇到一个比较特殊的问题。
mysql 语句如下:

update wms_cabinet_form set cabf_enabled=0
where cabf_id in (
SELECT wms_cabinet_form.cabf_id FROM wms_cabinet_form
Inner Join wms_cabinet ON wms_cabinet_form.cabf_cab_id = wms_cabinet.cab_id
Inner Join wms_cabinet_row ON wms_cabinet.cab_row_id =wms_cabinet_row.row_id
where wms_cabinet_row.row_site_id=27 and wms_cabinet_form.cabf_enabled=1)

运行时提出如下提示: You can't specify target table 'wms_cabinet_form' for update in FROM clause

运行 in 里面的 select 字句:

SELECT wms_cabinet_form.cabf_id FROM wms_cabinet_form
Inner Join wms_cabinet ON wms_cabinet_form.cabf_cab_id = wms_cabinet.cab_id
Inner Join wms_cabinet_row ON wms_cabinet.cab_row_id =wms_cabinet_row.row_id
where wms_cabinet_row.row_site_id=27 and wms_cabinet_form.cabf_enabled=1

可以正确 select 正确结果。再把结果直接写到 in 里面,改后语句如下:
update wms_cabinet_form set cabf_enabled=0 where cabf_id in ('113','114','115'),再运行可以正确执行更新。
到这一步开始想不明白,为什么用 select 子句运行会出错呢?以前在 mssql 这种写法是很常见的。
没办法了,唯有动用 baidu。找到两条记录。

原来原因是:mysql中不能这么用。 (等待mysql升级吧)。那串英文错误提示就是说,不能先select出同一表中的某些值,
再update这个表(在同一语句中)。 也找到替代方案,重写改写了 sql 。

改写后的 sql 如下所示,大家仔细区别一下。

update wms_cabinet_form set cabf_enabled=0 where cabf_id in (
SELECT a.cabf_id FROM (select tmp.* from wms_cabinet_form tmp) a
Inner Join wms_cabinet b ON a.cabf_cab_id = b.cab_id
Inner Join wms_cabinet_row c ON b.cab_row_id = c.row_id
where c.row_site_id=29 and a.cabf_enabled=1)

重点在 SELECT a.cabf_id FROM (select tmp.* from wms_cabinet_form tmp) a ,我 select tmp.* from wms_cabinet_form tmp 作为子集,
然后再 select a.cabf_id FROM 子集,这样就不会 select 和 update 都是同一个表。致此问题得到完美解决。

标签:mysql,specify,target,table
0
投稿

猜你喜欢

  • SQL语句练习实例之五 WMS系统中的关于LIFO或FIFO的问题分析

    2011-11-03 16:59:59
  • MySQL为什么临时表可以重名

    2024-01-15 21:28:27
  • Django查找网站项目根目录和对正则表达式的支持

    2023-04-09 15:50:37
  • GitHub上值得推荐的8个python 项目

    2021-01-11 22:40:12
  • 网站508规范(译)

    2008-04-03 13:26:00
  • xml文件调用css

    2008-09-05 17:12:00
  • tensorflow将图片保存为tfrecord和tfrecord的读取方式

    2022-01-22 11:32:04
  • SQL Server从安装到建库为新手寻找捷径

    2009-01-13 13:22:00
  • Python运用于数据分析的简单教程

    2023-08-14 07:49:13
  • python如何将一个四位数反向输出

    2023-03-21 16:42:40
  • 使用 Vue cli 3.0 构建自定义组件库的方法

    2024-05-05 09:07:50
  • scrapy 远程登录控制台的实现

    2023-05-22 14:27:00
  • Python Pillow Image.save 保存为jpg图片压缩问题

    2023-07-05 11:13:49
  • JavaScript 函数惰性载入的实现及其优点介绍

    2024-04-16 09:25:37
  • Python的3种运行方式:命令行窗口、Python解释器、IDLE的实现

    2023-02-03 13:47:45
  • SQL Server日志清除的两种方法

    2009-03-16 17:01:00
  • python 发送邮件的四种方法汇总

    2022-04-09 05:44:18
  • 如何使用五行Python代码轻松实现批量抠图

    2023-10-06 08:05:20
  • Python pytest.main()运行测试用例

    2023-08-18 02:57:52
  • Python入门之模块和包用法详解

    2021-08-28 10:58:14
  • asp之家 网络编程 m.aspxhome.com