gpt4 book ai didi

mysql - 多层次营销 SQL 查询来计算团队的营业额

转载 作者:行者123 更新时间:2023-11-29 03:19:05 25 4
gpt4 key购买 nike

我有一个看起来像这样的 users 表:

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 []

第三张表订单

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

预期结果,用SQL查询得到下表(create table mlm_team as select..)

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

有 SQL 专家可以帮助我吗?

最佳答案

按照以下步骤:

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

从此处查找 SQL Fiddle 详细信息 LINK .

关于mysql - 多层次营销 SQL 查询来计算团队的营业额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48224599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com