0

我找到了一些很好的资源,这些资源表明我应该能够将选择查询与更新合并,但我就是无法理解正确的格式。

我有一个为我获取信息的 select 语句,我几乎想使用这些结果来更新与accountIDselect 查询中的匹配的帐户表。

这是选择语句:

SELECT DISTINCT SUM(b.workers)*tt.mealTax as MealCost,b.townID,b.accountID
FROM buildings AS b
INNER JOIN town_tax AS tt ON tt.townID = b.townID
GROUP BY b.townID,b.accountID

所以简而言之,我希望将上述查询与以下内容合并:

UPDATE accounts AS a
SET a.wealth = a.wealth - MealCost

MealCost选择查询的结果在哪里。我确信有一种方法可以将其合并为一个,我只是无法将这些点连接起来以使其始终如一地运行,而无需分成两个查询。

4

1 回答 1

1

首先,当你有一个 group by 时,你不需要 distinct。

其次,您打算如何将这两个结果联系起来?SELECT 查询为每个帐户返回多行(每个城镇一个)。据推测,accounts 表只有一行。假设您想要更新的平均 MealCost。

得到这个的选择查询是:

SELECT accountID, avg(MealCost) as avg_Mealcost
FROM (SELECT SUM(b.workers)*tt.mealTax as MealCost, b.townID, b.accountID
      FROM buildings AS b INNER JOIN
           town_tax AS tt
           ON tt.townID = b.townID
      GROUP BY b.townID,b.accountID
     ) a
GROUP BY accountID

现在,要将其放入更新中,您可以使用如下语法:

UPDATE accounts
    set accounts.wealth = accounts.wealth + asum.avg_mealcost
    from (SELECT accountID, avg(MealCost) as avg_Mealcost
          FROM (SELECT SUM(b.workers)*tt.mealTax as MealCost, b.townID, b.accountID
                FROM buildings AS b INNER JOIN
                     town_tax AS tt
                     ON tt.townID = b.townID
                GROUP BY b.townID,b.accountID
               ) a
          GROUP BY accountID
         ) asum
    where accounts.accountid = asum.accountid

这使用 SQL Server 语法,我相信它与 Oracle 和大多数其他数据库相同。Mysql 将“from”子句放在“set”之前,并允许在“update accounts”上使用别名。

于 2012-05-30T02:22:48.330 回答