转载请注明出处,如果您觉得文章有用,就点个赞吧!
问题:
如何同一张表上查询到的数据更新回到同一张表中
准备测试数据
create table tb(
id int unsigned not null auto_increment primary key,
cid int not null,
name varchar(10) not null
)enigne=InnoDB
insert into tb values(null,0,'xyg'),(null,0,'china');
select * from tb;
+----+-----+-------+
| id | cid | name |
+----+-----+-------+
| 1 | 0 | xyg |
| 2 | 0 | china |
+----+-----+-------+
解决方案一:
update tb set cid=(select id from tb where name='xyg');
#会发现报错,如下:
ERROR 1093 (HY000): You can't specify target table 'test' for update in FROM clause
解决方案二:
update tb inner join (select id,name from tb where name='xyg') as t1 using(name) set tb.cid=t1.id
OK,发现成功了
select * from tb;
+----+-----+-------+
| id | cid | name |
+----+-----+-------+
| 1 | 1 | xyg |
| 2 | 0 | china |
+----+-----+-------+
知识扩展
-
对于方案一不成功的原因:
本人认为是 数据库认为会触发触发器造成死循环,所以限制了该功能 -
对于方案二可以成功的原因:
主要是方案实际是生成了临时表,规避方案一失败的原因,所以可以成功执行