我有以下表格 (表: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
我是如何完成这个的
答案 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
行中填充了列year
和month
,并且只想更新数据列(evep
, ...)来自reg_data3
的汇总值。
但如果情况并非如此,您希望INSERT
包括year
和month
在内的所有列,但能够使用相同的年份和月份值更新现有行,则可以使用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
约束(年,月){ p>