根据用户(MYSQL)更新状态总数(待定、确认、取消)

kx7yvsdv  于 2023-05-21  发布在  Mysql
关注(0)|答案(1)|浏览(197)

我有下表,我如何才能相应地更新每个状态的总计数。

客户表

客户IDCOUNT1COUNT2计数3
二百零一000
二百零二000

订单表

SIDCID状态
五零一三二百零一待定
五零一四二百零一待定
五○一五二百零二确认
五零一六二百零一已取消
五零一七二百零二待定
五零一八二百零一已取消

结果如下:

COUNT1 (PENDING)
COUNT2 (CONFIRMED)
COUNT3 (CANCELLED)
CIDCOUNT1COUNT2计数3
二百零一202
二百零二110
8yoxcaq7

8yoxcaq71#

SELECT cid,
       SUM(status = 'PENDING') AS count1,
       SUM(status = 'CONFIRMED') AS count2,
       SUM(status = 'CANCELLED') AS count3
FROM `order`
GROUP BY 1

因此

UPDATE customer
JOIN (
    SELECT cid,
           SUM(status = 'PENDING') AS count1,
           SUM(status = 'CONFIRMED') AS count2,
           SUM(status = 'CANCELLED') AS count3
    FROM `order`
    GROUP BY 1
    ) amounts USING (cid)
SET customer.count1 = amounts.count1, 
    customer.count2 = amounts.count2, 
    customer.count3 = amounts.count3

相关问题