mysql update語句根據子查詢結果把子查詢數據寫入修改字段


需求,應用場景

table1是統計信息表,里面存儲了商店id,一個商店一條數據,table2是訂單表,里面存儲了多個訂單,每條訂單有一個字段是table1的商店id,table3是商品表,存儲了多個商品,table2里面的每條數據在table3里面有1-N條商品數據,table1.shop_id=table2.shop_id,table2.order_id=table3.order_id,把table3同一個商店下面的商品數量統計一下,寫入到table1表的銷量統計字段里

mysql語句

update table1 t1, //修改t1表
(select sum(t3.num) as s , t2.shop_id as shop_id,t2.order_status as order_status
FROM table2 as t2
join table3 as t3
on t2.order_id = t3.order_id
WHERE
t2.order_status = 4 ) c //連表查詢t2,t3查詢結果別名c
set t1.sales_volume = c.s //t1.sales_volume = c.s 字段值
WHERE
t1.shop_id = c.shop_id and c.order_status = 4 //t1.shop_id = 查詢結果集的shop_id

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM