mysql不允許在同一個表上查詢和更新,例如下面sql語句嘗試將兩個表中相似行的數(shù)量記錄到字段cnt中。
update tb1 as outer_tb1
set cnt = (
select count(*) from tb1 as inner_tb1
where inner_tb1.type = outer_tb1.type
);
可以通過使用生成表的形式繞開上面的限制,mysql只會吧這個表當(dāng)做一個臨時表,實際上是執(zhí)行了兩個查詢,一個是子查詢的select,另一個是多表關(guān)聯(lián)的update,只是關(guān)聯(lián)的表是個臨時表。子查詢會在update語句打開表之前就完成,所以可以改為下面的方式實現(xiàn):
update tb1
inner join(
select type,count(*) as cnt
from tb1
group by type
) as der using(type)
set tb1.cnt = der.cnt;
(筆記)