多级营销SQL查询计算团队的营业额

时间:2018-01-12 10:44:42

标签: mysql sql tree mlm

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

ID NAME
1  Robin
2  Edward
3  Donald
4  Julie

第二张表 user_tree

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

第3张表订单

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

预期结果,使用SQL查询获取下表(使用select ..创建表mlm_team)

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

是否有SQL专家可以帮助我?

1 个答案:

答案 0 :(得分:0)

按照以下步骤操作:

- 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;

从此处LINK查找SQL小提琴详细信息。