如何从表2减去数据到表1

时间:2019-03-30 18:10:56

标签: mysql sql

我试图像这样减去并添加表中的现有值

表1

id       q      q_out    
1        10         0    
2        10         0

表2

id     q    
1      2
1      1
2      1
2      2

我希望在更新表1时得到此输出:

id     q      q_out
1      7       3   
2      7       3

但我得到以下输出:

id     q      q_out    
1      8       2    
2      9       1

这是我的查询

UPDATE 
    db_pro d 
    JOIN cart c ON d.pro_num = c.p_num 
SET 
    d.q = (d.q - c.q), 
    d.out_q = (d.out_q + c.q) 
WHERE 
    c.s_num='13-37478' and 
    c.class not like 'Books' and 
    c.remarks like 'On Process'

1 个答案:

答案 0 :(得分:1)

您需要加入表购物车的汇总值:

UPDATE 
    db_pro d 
    JOIN (
      select p_num, sum(q) q from cart 
      WHERE
        s_num='13-37478' and 
        class not like 'Books' and 
        remarks like 'On Process' 
      group by p_num
    ) c ON d.pro_num = c.p_num 
SET 
    d.q = (d.q - c.q), 
    d.out_q = (d.out_q + c.q)