mysql不允许select from后面指向用作update的表,有时候让人纠结。当然,有比创建无休止的临时表更好的办法。本文解释如何update一张表,同时在查询子句中使用select.
问题描述
假设我要update的表跟查询子句是同一张表,这样做有许多种原因,例如用统计数据更新表的字段(此时需要用group子句返回统计值),从某一条记录的字段update另一条记录,而不必使用非标准的语句,等等。举个例子:
create table apples(variety char(10) primary key, price int);
insert into apples values(‘fuji’, 5), (‘gala’, 6);
update apples
set price = (select price from apples where variety = ‘gala’)
where variety = ‘fuji’;
错误提示是:error 1093 (hy000): you can’t specify target table ‘apples’ for update in from clause. mysql手册update documentation这下面有说明 : “currently, you cannot update a table and select from the same table in a subquery.”
在这个例子中,要解决问题也十分简单,但有时候不得不通过查询子句来update目标。好在我们有办法。
解决办法
既然mysql是通过临时表来实现from子句里面的嵌套查询,那么把嵌套查询装进另外一个嵌套查询里,可使from子句查询和保存都是在临时表里进行,然后间接地在外围查询被引用。下面的语句是正确的:
update apples
set price = (
select price from (
select * from apples
) as x
where variety = ‘gala’)
where variety = ‘fuji’;
以上就是MySQL数据库在select同时进行update操作的方法的内容,更多相关内容请关注PHP中文网(www.php.cn)!
法语写作助手
法语助手旗下的AI智能写作平台,支持语法、拼写自动纠错,一键改写、润色你的法语作文。
31 查看详情 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/420732.html
微信扫一扫
支付宝扫一扫