0

私はこのようなデータベーステーブルを持っています。

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

今、MYSQL クエリを使用して、ユーザー ID 1 の下の各子の残高を更新したいと考えています。

2、3、4 は '1' の子と孫であるため、balance=balance + 10 を更新すると、結果は次のようになります。

     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 に答える