使用另一个表更新mysql表的多个列

时间:2013-12-10 05:30:00

标签: mysql

我有以下表格 (表:avg_month_val1

year                       
month        
evep                
sunshine_hrs             
rainfall     
max_temp               
min_temp  

表:reg_data3

id         
date                
time                  
rainfall                
evep                         
max_temp                   
min_temp    
sunshine_hrs

我想使用reg_data3来更新avg_month_val1表 我跟随 How do you update multiple fields from another table in mysql?

这是我的查询

UPDATE `avg_month_val1` a,`reg_data3` b SET
a.`year`=YEAR(b.`date`),
a.`month`=MONTH(b.`date`),
a.`evep`=ROUND(AVG(b.evep),2),
a.`max_temp`=ROUND(AVG(b.max_temp),2), 
a.`min_temp`=ROUND(AVG(b.min_temp),2) ,
a.`rainfall`=ROUND(SUM(b.rainfall),2), 
a.`sunshine_hrs`=ROUND(AVG(b.sunshine_hrs),2)
WHERE a.`year`=YEAR(b.`date`)

但它会出现以下错误

Error Code: 1111
Invalid use of group function

我是如何完成这个的

1 个答案:

答案 0 :(得分:4)

以这种方式试试

UPDATE avg_month_val1 t JOIN 
(
  SELECT YEAR(date) year,
         MONTH(date) month,
         ROUND(AVG(evep), 2) evep,
         ROUND(AVG(max_temp), 2) max_temp,
         ROUND(AVG(min_temp), 2) min_temp,
         ROUND(SUM(rainfall), 2) rainfall,
         ROUND(AVG(sunshine_hrs), 2) sunshine_hrs
    FROM reg_data3
   GROUP BY YEAR(date), MONTH(date)
) s 
    ON t.year = s.year
   AND t.month = s.month
   SET t.evep = s.evep,
       t.max_temp = s.max_temp, 
       t.min_temp = s.min_temp, 
       t.rainfall = s.rainfall, 
       t.sunshine_hrs = s.sunshine_hrs 

使用UPDATE表示您已在表avg_month_val1行中填充了列yearmonth,并且只想更新数据列(evep, ...)来自reg_data3的汇总值。

但如果情况并非如此,您希望INSERT包括yearmonth在内的所有列,但能够使用相同的年份和月份值更新现有行,则可以使用ON DUPLICATE KEY条款

INSERT INTO avg_month_val1 (year, month, evep, max_temp, min_temp, rainfall, sunshine_hrs)
SELECT YEAR(date) year,
       MONTH(date) month,
       ROUND(AVG(evep), 2) evep,
       ROUND(AVG(max_temp), 2) max_temp,
       ROUND(AVG(min_temp), 2) min_temp,
       ROUND(SUM(rainfall), 2) rainfall,
       ROUND(AVG(sunshine_hrs), 2) sunshine_hrs
  FROM reg_data3
 GROUP BY YEAR(date), MONTH(date)
 ON DUPLICATE KEY UPDATE
       evep = VALUES(evep),
       max_temp = VALUES(max_temp), 
       min_temp = VALUES(min_temp), 
       rainfall = VALUES(rainfall), 
       sunshine_hrs = VALUES(sunshine_hrs)

为了实现这一目标,您必须确保UNIQUE PRIMARY KEY或avg_month_val1约束(年,月)