SQL Update表基于另一个表

时间:2016-02-24 17:02:22

标签: mysql

我有2张桌子 T1(月份+年份是唯一的)

 month  year    amount 
  10      2015     5000  
  11      2015     4000

T2

  month   year     amount 
  10      2015      100
  10      2015      200
  10      2015      200
  11      2015      200

我想按如下方式更新T1的金额字段 T1.amount = T1.amount - (匹配月份,年份的T2金额之和)

因此更新后T1应如下所示

  month    year   amount
     10       2015    4500 
     11       2015    3800

我不是SQL专家,请建议SQL实现上述功能,谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用UPDATE JOIN对包含每月/每年Table2总和的派生表执行操作:

UPDATE TABLE1 AS T1
JOIN ( SELECT month, year, SUM(amount)  AS amount
       FROM TABLE2 
       GROUP BY month, year) AS T2
  ON T1.month = T2.month AND T1.year = T2.year
SET T1.amount =   T1.amount - T2.amount;

Demo here

修改

在sqlite中,您必须使用相关子查询来执行UPDATE

UPDATE TABLE1 
SET amount =  amount - (SELECT SUM(amount)  
                        FROM TABLE2 
                        WHERE TABLE1.month = TABLE2.month AND 
                        TABLE1.year = TABLE2.year);

Demo here

答案 1 :(得分:1)

Dispose

SQL FIDDLE

<强>解释

内部查询将总计每个(月,年)对的金额。

内部查询:

UPDATE T1 
INNER JOIN 
(    
  SELECT 
    `month`,
    `year`,
     SUM(amount) totalAmount
  FROM T2
  GROUP BY `month`,`year`  ) t
ON t.`month` = T1.`month` AND t.`year` = T1.`year`
SET T1.amount = T1.amount - t.totalAmount;

对于您的样本数据,它返回如下结果:

我将其命名为SELECT `month`, `year`, SUM(amount) totalAmount FROM T2 GROUP BY `month`,`year` table

t

现在,如果您将此month year totalAmount 10 2015 500 11 2015 200 表加入T1表tmonth

这意味着仅当year T1.month equals t.month AND 时才会加入来自两个表的行,然后您将更新相应数量的T1表格行,如下所示:

and T1.year equals t.year

因此,在此次更新后,您的T1.amount = T1.amount - t.totalAmount应如下所示:

T1 table

结果:

SELECT 
*
FROM T1

修改 在期望查询在SqlLite中工作时,您标记了问题month year amount 10 2015 4500 11 2015 3800 。 SQLlite doesn't support JOIN in Update statements

Sqllite查询:

MySQL