sql高手请进!非常急!谢谢!

来源:百度知道 编辑:UC知道 时间:2024/06/18 17:45:00
数据库是这样的biao1
id parentId money quanxian
1 1,2,3,4 100 1
2 0,2,3,4 110 2
3 0,0,3,4 120 3
4 0,0,0,4 130 4
其中parentId是上级ID号 比如ID 1 的上级是2 2的上级是3 3的上级是4 所以就写1,2,3,4

现在是这样的 我想修改4的money 改为120 所以我想让所有他的下级都根据相应的减少 (4本来比3多10(130-120) 现在4为120 所以3就变成 120-(130-120)=110 以此类推下去) 这样的sql语句写不出来.....求救~~~~~
不是每行都减固定值 是跟上级的money相差多少 然后相应的减 比如
id parentId money quanxian
1 1,2,3,4 100 1
2 0,2,3,4 120 2
3 0,0,3,4 120 3
4 0,0,0,4 130 4
如果 4改为120 那么3=120-(130-120)=110
2=110-(120-120)=110
1=110-(120-100)=90

回答者: 余兴斌 - 举人 四级 感谢你的回答! 关键是这个上级的级别个数是可变的 就是说不一定是3个上级 可能有10个 20个上级 .

建议增加“cha”列,记录与上级的差值,把PARENTID列分为三列如下:
id parentid1 parentid2 parentid3 money quanxian cha
1 2 3 4 100 1 20
2 3 4 null 120 2 0
3 4 null null 120 3 10
4 null null null 130 4 0
update biao1 set money=120 where id=4
update biao1 set money=(select money from biao1 where id=a.parentid1)-cha from biao1 a where parentid1=4
update biao1 set money=(select money from biao1 where id=a.parentid1)-cha from biao1 a where parentid2=4
update biao1 set money=(select money from biao1 where id=a.parentid1)-cha from biao1 a where parentid3=4

----------------------
级数可变的话,parentid列值应该为:
id parentid money quanxian cha
1 2,3,4 100 1 20
2 3,4 120 2 0
3 4 120 3 10
4 null 130 4 0
用循环语句,从1到parentid列最长的值(跳过逗号),update biao1 set money=(select money from biao1 where id=substring(a.parentid,1,1))-cha from biao1 a where substring(parentid,n,1)='4'

如果是每行的MONEY都减固定值10的话可以写
update biao1 set mon