标签:
select goods_id,goods_type,goods_name,in_buy_price,ROUND(sum(in_total_price)/sum(in_amount),2),count(*) from in_warehouse_detail group by goods_id,goods_type,goods_name order by goods_id,goods_type,goods_name
查询结果如下:
另一张关联表【通过goods表的goods_Id和in_warehouse_detail表的goods_id关联】
select goods_Id,goods_name,goods_sel_price,goods_buy_price from goods
希望实现效果
①根据主外键关联将in_warehouse_detail查询到的平均值【ROUND(sum(in_total_price)/sum(in_amount),2)】列数据更新到goods表的goods_buy_price 列
②查询in_warehouse_detail表in_buy_price 和 ROUND(avg(in_buy_price),2)这两列不同值 的数据
③查询goods表goods_sel_price 列和in_warehouse_detail表 ROUND(avg(in_buy_price),2)这两列不同值 的数据
后来自己琢磨出来点东西 觉得得使用临时表来处理 查询当前要做的事情后整合发现
select goods_Id,goods_name,goods_sel_price,goods_buy_price from goods
select g.goods_Id,g.goods_name,g.goods_type,g.goods_sel_price,g.goods_buy_price ,a.junjia from goods g,avg_prices a where g.goods_Id = a.goods_id and g.goods_sel_price != a.junjia
将上面的查询结果塞入临时表
DROP TABLE IF EXISTS avg_prices; create table avg_prices as select goods_id,goods_type,goods_name,in_buy_price, ROUND(sum(in_total_price)/sum(in_amount),2) as ‘junjia‘,count(*) from scm.in_warehouse_detail group by goods_id,goods_type,goods_name order by goods_id,goods_type,goods_name;
查询生成的临时表里的数据
select * from avg_prices
那么解决的问题就变成了 如何 将第一张表里junjia字段根据id 条件批量更新到第二张表goods表内goods_buy_price字段值
通过个人不断测试终于实现
多亏 沉沦启发我语句
update a.junjia from goods g,avg_prices a set g.goods_sel_price = a.junji where g.goods_Id = a.goods_id
实现语句如下 可加个定时器 每日执行 就能解决实时均价这个难题
1 DROP TABLE IF EXISTS avg_prices; 2 3 create table avg_prices as 4 select goods_id,goods_type,goods_name,in_buy_price, 5 ROUND(sum(in_total_price)/sum(in_amount),2) as ‘junjia‘,count(*) from scm.in_warehouse_detail 6 group by goods_id,goods_type,goods_name 7 order by goods_id,goods_type,goods_name;
源码
---------如果当前数据库里面存在 均价临时表 则删除掉--------- DROP TABLE IF EXISTS avg_prices; ---------创建均价临时表并将查询结果填充入临时表--------- create table avg_prices as select goods_id,goods_type,goods_name,in_buy_price, ROUND(sum(in_total_price)/sum(in_amount),2) as ‘junjia‘,count(*) from scm.in_warehouse_detail group by goods_id,goods_type,goods_name order by goods_id,goods_type,goods_name; ---------根据ID为关联 批量更新goods表 update avg_prices a,goods g set g.goods_buy_price = a.junjia where g.goods_Id = a.goods_id and g.goods_sel_price != a.junjia ;
库存也可这样尝试 批量更新goods表
标签:
原文地址:http://www.cnblogs.com/zhangdashao/p/5395976.html