日期:2014-05-17  浏览次数:20793 次

自联表怎么更新的问题。
问题就是将7月字段abcclass为null的值,替换成3月该字段的abcclass值



就是一个产品表p_data,每个月都插入一次这个月的产品数据,我写的sql通不过

update 

//2012年7月有很多abcclass字段是null的
(select * from p_data a where a.year=2012 and a.month=7 and a.abcclass is null) y

join

//2012年3月大多数abcclass字段是有值的,就以3月为准
(select * from p_data a where a.year=2012 and a.month=3) x

on(x.productcode=y.productcode)

set y.abcclass=x.abcclass //将7月为null的abcclass字段等于3月份abcclass字段

------解决方案--------------------
SQL code

--try
update p_data
    set abcclass=(select abcclass from p_data a where p_data.productcode=a.productcode and  a.year=2012 and a.month=3)
    where p_data.year=2012 and p_data.month=7 and p_data.abcclass is null;

------解决方案--------------------
一楼正解
------解决方案--------------------
update p_data
set abcclass=(select abcclass from p_data a where p_data.productcode=a.productcode and a.year=2012 and a.month=3)
where p_data.year=2012 and p_data.month=7 and p_data.abcclass is null;

------解决方案--------------------
update p_data a
set abcclass=(select abcclass from p_data a where p_data.productcode=a.productcode and a.year=2012 and a.month=3) b
where a.year=2012 and a.month=7 and a.abcclass is null and a.id = b.id;

上面的ID都是你查询出来的同一条记录的值。