如何用另一个计算平均值的查询结果更新MySQL表

时间:2018-02-12 02:22:09

标签: mysql sql

我想在我的其他表格中使用所有价格值的AVG更新表格。似乎无法让它发挥作用。

Update price_avg set price = (select avg(price) from ((select price from table1) union all
  (select price from table2) union all
  (select price from table3) union all
  (select price from table4) union all
  (select price from table5) union all
  (select price from table6) union all
  (select price from table7) )) as t);

以上返回0行受影响。

运行这确实给了我平均价格;

select avg(price) from ((select price from table1) union all
  (select price from table2) union all
  (select price from table3) union all
  (select price from table4) union all
  (select price from table5) union all
  (select price from table6) union all
  (select price from table7)) as t;

或者我也很高兴将上述计算的值保存为PHP变量,但也无法使其工作。

2 个答案:

答案 0 :(得分:1)

括号中有些不对劲。试试这个:

Update price_avg
    set price = (select avg(price)
                 from ((select price from table1) union all
                       (select price from table2) union all
                       (select price from table3) union all
                       (select price from table4) union all
                       (select price from table5) union all
                       (select price from table6) union all
                       (select price from table7)
                      ) t
                );

答案 1 :(得分:0)

看起来我真正想做的是使用insert而不是update。这就是需要改变的一切。我的桌子是空的,所以没有什么可以更新。使用更新我应该使用WHERE命令指定要更新的行。