0

我有一个这样的数据库表。

     userID         RefralID         balance
        1              0               0
        2              1               0
        3              2               0
        4              3               0
        5              8               0

现在我想要一个 MYSQL 查询来更新用户 ID 1 下每个孩子的余额。从 10 小时起就卡在那里,但找不到所需的解决方案。

如果我们更新 balance=balance + 10 其中 userID = '1',结果应该是这样的,因为 2,3,4 是 '1' 的孩子和孙子,所以他们的余额应该更新

     userID         RefralID         balance
        1              0               0
        2              1               10
        3              2               10
        4              3               10
        5              8               0
4

2 回答 2

2
update tblA T2 join
 (
   SELECT 
        @r AS _id,
        (SELECT @r := userid FROM tblA WHERE refralid = _id limit 1) AS userid,
        @l := @l + 1 AS lvl
    FROM
        (SELECT @r := 1, @l := 0) vars,
        tblA m
    ) T1
ON T1._id = T2.userid  
set balance=balance+10 
where T2.userid<>1

@r := 1
T2.userid<>1 

The value 1 above is the userid=1

可以删除@l(级别)作为参考。

http://sqlfiddle.com/#!2/e606a/2

于 2012-10-18T07:50:55.197 回答
1

一般的方法是:

create table temp1 (int id);
create table temp2 (int id);

insert into temp1 select ReferalID from your_table where userID = 1

while exists (select 1 from temp1)
begin
       truncate table temp2

       update your_table 
       set balance = balance + 10 
       where userID in (select * from temp1)

       insert into temp2 select * from temp1

       truncate table temp1

       insert into temp1 
       select ReferalID 
       from your_table 
       where userID in (select * from temp2)       
end
于 2012-10-18T12:38:49.557 回答