MySQL 如何对同一张表来查询并update ?

时间:2021-07-28 00:42:25

MySql 不允许对同一张表来查询并update的。

如下面的SQL则不能运行。

update thb As outer_thb

set cnt=(

select count(*) from thb as innter_thb

where  innter_thb.type=outer_thb.type);


可以通过inner方式来达到这个目的,如下所示。


update 

thb inner join  ( 

select count(*) as cnt from thb 

group by thb.type ) as inner_thb  USING (type) 

set thb.cnt=inner_thb. cnt;


Update XXX set XXX where 这种写法大家都知道,

这里update和delete支持inner join的update 的定法

update tb_User
set pass=''
from tb_User usr
inner join tb_Address addr on usr.nAddressFK = addr.nAddressID
where usr.id=123

update的格式是

update t1 set t1.name=’Liu’ from t1 inner join t2 on t1.id = t2.tid

delete 语句也是类似

delete from t1 from t1 inner join t2 on t1.id = t2.tid