0

所以我有 3 个表,我需要从前 2 个表中计算一个值,然后用该值更新第三个表中的一个字段,我遇到了一个错误。

UPDATE Characters AS c
SET c.Total_DKP = (
(SELECT c.Initial_DKP
FROM c
WHERE c.Name='harrian')-
(SELECT SUM(a.DKP_Change)
FROM Attendance AS a 
WHERE a.Name = 'harrian')
              )
WHERE c.Name = 'harrian' ;

它给出了错误

Table 'harrian.c' doesn't exist

但是当我跑步时

UPDATE Characters AS c
SET c.Total_DKP = ( SELECT SUM(a.DKP_Change) 
                    FROM Attendance AS a 
                    WHERE a.Name = 'harrian'
                  )
WHERE c.Name = 'harrian'

我没有问题,谁能告诉我第一个块有什么问题?

这是完整的查询-

UPDATE Characters AS c
SET c.Total_DKP = (
(SELECT c.Inital_DKP FROM Characters AS c WHERE c.Name = 'harrian')
+(SELECT SUM(a.DKP_Change) FROM Attendance AS a WHERE a.Name = 'harrian')
+(SELECT SUM(b.Cost) FROM Raid_Drops AS b WHERE b.Player_Name = 'harrian')
)
WHERE c.Name = 'harrian' ;

我现在收到此错误

You can't specify target table 'c' for update in FROM clause
4

2 回答 2

1

您的第一个子查询是:

SELECT c.Initial_DKP FROM c WHERE c.Name='harrian'

而不是FROM c我认为你的意思是FROM Characters

SELECT Initial_DKP FROM Characters WHERE Name='harrian'

但如果是这样的话,整个 UPDATE 最好写成

UPDATE Characters AS c
SET c.Total_DKP = c.Initial_DKP - (
  SELECT SUM(a.DKP_Change)
  FROM Attendance AS a 
  WHERE a.Name = 'harrian'
)
WHERE c.Name = 'harrian';

因为更新语句不能使用它在子查询中更新的表。

于 2012-12-07T21:58:23.133 回答
0

Name = 'harrian'如果表中的行不能超过一行Characters(例如 if Nameis UNIQUE),您可以使用:

UPDATE Characters AS c
SET c.Total_DKP = (
  c.Inital_DKP
  + (SELECT SUM(a.DKP_Change) FROM Attendance AS a WHERE a.Name = 'harrian')
  + (SELECT SUM(b.Cost) FROM Raid_Drops AS b WHERE b.Player_Name = 'harrian')
  )
WHERE c.Name = 'harrian' ;

不需要上面的一些括号。此外,为了避免空表产生的行AttendanceRaid_Drops没有行Name = 'harrian'的情况,您需要将 Null 转换为零:NULLSUM()

UPDATE Characters AS c
SET c.Total_DKP = 
  c.Inital_DKP
  + COALESCE( (SELECT SUM(a.DKP_Change) FROM Attendance AS a 
               WHERE a.Name = 'harrian')
            ), 0)
  + COALESCE( (SELECT SUM(b.Cost) FROM Raid_Drops AS b 
               WHERE b.Player_Name = 'harrian')
            ), 0)
WHERE c.Name = 'harrian' ;
于 2012-12-07T22:57:24.583 回答