gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:56:16 26 4
gpt4 key购买 nike

我有下表(表: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

我是怎么做到的

最佳答案

这样试试

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 的行,并且仅想要使用 reg_data3 中的聚合值更新数据列(evep,...)。

但如果不是这种情况,并且您想要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)

为了让它工作,你必须确保你有 UNIQUEPRIMARY KEY constraint on (year, month) in avg_month_val1

关于mysql - 使用另一个表更新mysql表多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20486870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com