使用另一个表列中的平均数据更新列

时间:2010-06-04 12:02:46

标签: mysql

我写了一个这样的命令来更新一个表中的列,其中包含来自另一个表的avg列...它给出了错误

UPDATE college_rating,products set 
property1_avg =  avg(college_rating.rating1),
property2_avg =  avg(college_rating.rating2),
property3_avg =  avg(college_rating.rating3),
property4_avg =  avg(college_rating.rating4),
property5_avg =  avg(college_rating.rating5),
property6_avg =  avg(college_rating.rating6),
property7_avg =  avg(college_rating.rating7),
property8_avg =  avg(college_rating.rating8),
property9_avg =  avg(college_rating.rating9),
property10_avg =  avg(college_rating.rating10),
property11_avg =  avg(college_rating.rating11),
property12_avg =  avg(college_rating.rating12),
property13_avg =  avg(college_rating.rating13),
property14_avg =  avg(college_rating.rating14),
property15_avg =  avg(college_rating.rating15) 
where products.alias = concat(college_rating.property1,'-',college_rating.property2,'-',college_rating.property3) 
group by college_rating.property1,college_rating.property2, college_rating.property3

3 个答案:

答案 0 :(得分:1)

MySQL多表更新语法不允许使用group by。

您可以通过将聚合移动到子查询并在多表更新中加入该子查询来完成您要执行的操作。

这样的事情应该有效:

update products p
inner join (
  select concat(property1,'-',property2,'-',property3) as alias,
  avg(rating1) as property1_avg,
  avg(rating2) as property2_avg,
  avg(rating3) as property3_avg,
  avg(rating4) as property4_avg,
  avg(rating5) as property5_avg,
  avg(rating6) as property6_avg,
  avg(rating7) as property7_avg,
  avg(rating8) as property8_avg,
  avg(rating9) as property9_avg,
  avg(rating10) as property10_avg,
  avg(rating11) as property11_avg,
  avg(rating12) as property12_avg,
  avg(rating13) as property13_avg,
  avg(rating14) as property14_avg,
  avg(rating15) as property15_avg 
  from college_rating
  group by property1,property2, property3
) as r on r.alias = p.alias
set p.property1_avg = r.property1_avg,
p.property2_avg = r.property2_avg,
p.property3_avg = r.property3_avg,
p.property4_avg = r.property4_avg,
p.property5_avg = r.property5_avg,
p.property6_avg = r.property6_avg,
p.property7_avg = r.property7_avg,
p.property8_avg = r.property8_avg,
p.property9_avg = r.property9_avg,
p.property10_avg = r.property10_avg,
p.property11_avg = r.property11_avg,
p.property12_avg = r.property12_avg,
p.property13_avg = r.property13_avg,
p.property14_avg = r.property14_avg,
p.property15_avg = r.property15_avg;

答案 1 :(得分:0)

你得到的错误是什么?并且您需要有一个WHERE子句,除非您希望UPDATE查询应用于所有记录

答案 2 :(得分:0)

我认为你需要使用子查询,我不确定你是否可以在MySQL中更新两个表,至少不能没有前缀属性。