引用另一列中的计算值

时间:2014-06-25 23:37:15

标签: mysql sql phpmyadmin

我正在尝试将计算值显示在另一个表的另一列中。 有人可以解释为什么这不起作用

CREATE TABLE #Medition (ID int,AVG decimal(18,4))
INSERT INTO #Medition (ID, AVG) 
SELECT ID, SUM(125Hz + 250Hz + 500Hz + 750Hz + 1000Hz + 1500Hz + 2000Hz + 3000Hz + 4000Hz + 6000Hz + 8000Hz)/11 AS AVG FROM tonvarden 
UPDATE matningar  SET matningar.tonmedelvarde =
#Medition.AVG FROM matningar INNER JOIN #Medition ON matningar.ID =#Medition.ID
 DROP TABLE #Medition

我收到此错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO #Medition (ID, AVG) SELECT ID, SUM(125Hz + 250Hz + 500Hz + 750Hz + ' at line 2

1 个答案:

答案 0 :(得分:0)

无需创建临时表来执行此操作。

UPDATE matningar a
join tonvarden b on a.ID = b.ID
set a.tonmedelvarde = (`125Hz` + `250Hz` + `500Hz` + `750Hz` + `1000Hz` + 
                          `1500Hz` + `2000Hz` + `3000Hz` + `4000Hz` + `6000Hz` + 
                          `8000Hz`)/11;

如果您想在将新行插入tonvarden时更新matningar,则可以创建以下触发器:

create trigger update_matningar before insert on tonvarden
for each row 
update matningar 
set tonmedelvarde = 
    (new.`125Hz` + new.`250Hz` + new.`500Hz` + new.`750Hz` 
        + new.`1000Hz` + new.`1500Hz` + new.`2000Hz` 
        + new.`3000Hz` + new.`4000Hz` + new.`6000Hz` 
        + new.`8000Hz`)/11
where id = new.id;