0

我有一个查询,我似乎无法在 MySQL 的 SUM 函数中操作:

这是我想要的:

将 account_seeds 更新为
内部联接 b AS b ON b.accountID = a.accountID AND a.areaID = b.areaID 内部
联接 b_seed AS s ON s.buildingID = b.buildingID 内部
联接 seed_class AS c ON c.seedID = s。 seedID
SET a.amount = a.amount + SUM(s.amount)
其中 b.status='active' AND a.seedID = s.seedID

现在它显然不会让我在不分离的情况下在更新中使用 SUM。我曾尝试加入选择查询,但无法完全理解它。基本前提是我有多个建筑物(行),它们的种子值将增加特定帐户该区域中该类型的总种子数。如果没有总和,它只会更新具有匹配种子值的建筑物之一

4

2 回答 2

2
UPDATE 
    account_seeds AS a 
  INNER JOIN 
    ( SELECT b.accountID, b.areaID, s.seedID
           , SUM(s.amount) AS add_on 
      FROM b AS b 
        INNER JOIN b_seed AS s 
          ON s.buildingID = b.buildingID
        INNER JOIN seed_class AS c 
          ON c.seedID = s.seedID
      WHERE b.status = 'active' 
      GROUP BY b.accountID, b.areaID, s.seedID
    ) AS g
    ON  g.accountID = a.accountID 
    AND g.areaID = a.areaID
    AND g.seedID = a.seedID
SET 
    a.amount = a.amount + g.add_on ;
于 2012-07-08T14:17:01.313 回答
1

也许您可以使用嵌套查询:

UPDATE account_seeds AS a 
INNER JOIN b AS b ON b.accountID = a.accountID AND a.areaID = b.areaID
INNER JOIN b_seed AS s ON s.buildingID = b.buildingID
INNER JOIN seed_class AS c ON c.seedID = s.seedID
SET a.amount = a.amount + (SELECT SUM(amount) FROM b_seed)
WHERE b.status='active' AND a.seedID = s.seedID

你能试试吗?

于 2012-07-08T12:04:28.927 回答