我需要创建一个选择,以便在多级营销系统中以HTML格式列出树。我的关系表有:
Members_relations:
memberID parentID
1 2
1 3
1 4
5 NULL
6 NULL
7 8
4 7
Members_sales:
Id Sale
1 500
2 300
3 400
4 150
5 200
6 0
7 0
8 0
例如,如果我需要检索memberID 1上方的成员数量,并且我需要在成员1之上的每个成员的其他选择中检索我需要另外选择以获取有关成员1之上的每个人的销售额,例如,可以为会员1支付佣金。
如何进行此查询?请记住,这是一个多层次的营销系统,
答案 0 :(得分:0)
这是一个示例解决方案。我已经改变了你的树形结构,以便更有意义地回答。可以自由地将代码与您环境中的确切要求(sechema,commisions,...)相匹配。
Members_relations
parentID memberID <--- OP, be carefull here
1 2
1 3
1 4
7 8
4 7
10 100
Members_sales:
Id Sale
1 500
2 300
3 400
4 150
5 200
6 0
7 0
8 0
10 999
100 888
要弄明白,孩子们发现时自我加入:
DELIMITER $$
DROP PROCEDURE IF EXISTS letsgo;
CREATE PROCEDURE letsgo ( IN id int ) BEGIN
DECLARE nR INT;
DROP TEMPORARY TABLE IF EXISTS children;
CREATE TEMPORARY TABLE children AS (SELECT id as Id);
DROP TEMPORARY TABLE IF EXISTS children_prev;
CREATE TEMPORARY TABLE children_prev AS (SELECT id as Id );
SET nR = ( SELECT count(*) FROM children );
WHILE ( nR > 0 ) DO
DROP TEMPORARY TABLE IF EXISTS children_aux;
CREATE TEMPORARY TABLE children_aux AS (
SELECT memberID as id
FROM Members_relations R
INNER JOIN children_prev C on C.id = R.parentID
);
SET nR = ( SELECT count(*) FROM children_aux );
INSERT INTO children
SELECT * FROM children_aux;
TRUNCATE TABLE children_prev;
INSERT INTO children_prev
SELECT * FROM children_aux;
END WHILE;
SELECT SUM( Sale )
FROM Members_sales S
INNER JOIN children C on C.id = S.Id;
END;
$$
DELIMITER ;
<强>测试强>
mysql> call letsgo(1);
+-------------+
| SUM( Sale ) |
+-------------+
| 1350 |
+-------------+
1 row in set (0.16 sec)
mysql> call letsgo(100);
+-------------+
| SUM( Sale ) |
+-------------+
| 888 |
+-------------+
1 row in set (0.06 sec)
注意:我为脏解决方案道歉,但这是MySQL:没有CTE,没有选择函数的递归,没有DO-WHILE,......
注意:请记住,在许多国家/地区,法律不允许道德规范和禁止多层次营销计划。