多级营销sql查询,计算团队营业额

yhived7q  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(265)

我有一个用户表,看起来像这样:

ID NAME
1  Robin
2  Edward
3  Donald
4  Julie

第二个表用户目录树

ID USER_ID TREE
1  1       ["2","3","4"]
2  2       ["3","4"]
3  3       ["4"]
4  4       []

第三张table

ID AMOUNT USER_ID
1  150    2
2  300    3
3  200    4
4  500    3

根据预期结果,使用sql查询获取下表(create table mlm\u team as select..)

ID USER_ID TEAM_SUM
1  1       1150
2  2       1000
3  3       200

有sqlMaven能帮我吗?

djp7away

djp7away1#

遵循以下步骤:

- Create table and insert record.
- Get JSON type for array value
- Use "JSON_CONTAINS" for find MLM chain

请在此处解释:

create table users(id int, name varchar(50));
create table user_tree(id int, user_id int, tree json );
create table orders(id int, amount int, user_id int);

insert into users values(1,  'Robin');
insert into users values(2,  'Edward');
insert into users values(3 , 'Donald');
insert into users values(4 , 'Julie');

select * from users;

insert into user_tree values(1,  1 ,      '["2","3","4"]');
insert into user_tree values(2 , 2  ,     '["3","4"]');
insert into user_tree values(3 , 3  ,     '["4"]');
insert into user_tree values(4 , 4  ,     '[]');

select * from user_tree;

 insert into orders values(1 , 150  ,  2);
    insert into orders values(2 , 300  ,  3);
    insert into orders values(3 , 200  ,  4);
    insert into orders values(4 , 500 ,   3);

 select * from orders;

-此处为最终查询:

SELECT u1.id, u1.user_id as user_id, sum(amount)
FROM user_tree u1
left outer join user_tree u2 on JSON_CONTAINS(u1.tree, concat('["', u2.user_id ,'"]'))
left outer join orders o1 on o1.user_id = u2.user_id
where u2.user_id
group by u1.id, u1.user_id
order by u1.id;

从此处链接查找SQLFiddle详细信息。

相关问题