mysql在同一個表上查詢和更新
mysql不允許對同一張表同時進行查詢和更新。
錯誤例子:
update tbl as outer_tbl set cnt = (select count(*) from tbl as inner_tbl where inner_tbl.type = outer_tbl.type);
解決辦法:可以通過使用生成表的形式來繞過上面的限制,讓mysql把這個表當作一個臨時表來處理。實際上,這樣子就執行了兩個查詢:一個是子查詢中的select語句,另外一個是多表關聯update。子查詢在update語句打開表之前就完成,所以能夠正常執行。
正確例子:
update tbl inner join (select type, count(*) as cnt from tbl group by type) as der using(type) set tbl.cnt = der.cnt;