计算使用2个表并报告给第3个

时间:2012-12-07 21:54:32

标签: mysql

所以我有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

2 个答案:

答案 0 :(得分: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';

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

答案 1 :(得分:0)

如果表Name = 'harrian'中的Characters行不超过一行(例如NameUNIQUE),则可以使用:

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将在空表上生成SUM()的情况,你需要将Null转换为零:

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' ;