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

    xiaoxiao2021-03-25  62

    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

    转载请注明原文地址: https://ju.6miu.com/read-18193.html

    最新回复(0)