MySQL查询关闭表
当前USER表:
Field Type
id int(11)
firstname varchar(64)
lastname varchar(64)
status varchar(5)
permission smallint(5)
当前USER_RELATIONS表:(它有2个FOREIGN KEY - 祖先 - > USER.id - 后代 - > USER.id)
Field Type
relationId int(11)
ancestor int(11)
descendant int(11)
length int(11)
当前TRANSACTIONS表:(它有1个FOREIGN KEY - chid-> USER.id)
Field Type
id int(11)
chid int(11)
date date
amt varchar(16)
所有关系都正确设置,并在用户加入并输入引用他的另一用户的引用时创建,从而创建分层树。
之前我试图正确地获得这个设置,并从“Puggan Se”得到了一些很好的帮助,他们指出我在闭合表的方向。
目前,我可以看到一个单一原始引用者(祖先)的所有引用用户(后代)的整棵树。 我们还设置了一个自动调平系统,可以对每个已经提供预定数量的后代的用户进行调整。
我们现在增加了一家商店,并希望为每位用户提供一些参考资料,并邀请其他用户加入和购物。 基于其树状结构,“小东西”基本上是销售额的百分比。
解释:
1: A invited B, C & D -> B invited E,F -> C invited G -> D invited no-one
2: A moves to status=2(because he invited 3) -> B moves to status=1 (cause he invited 2)-> C & D remain on status=0 (because minimum required invites = 2)
3: Now when B, C & D purchases something from the shop, A should ge a little something back. Because A is status 2, he will get X % for all status=1 sales and Y % for all status=0 sales
4: In the event that B surpases A in status, A will NOT get a "little something" back.
5: status=0 levels do not get something back.
问题:我希望某人查看MySQL查询,并告诉我我是否正确执行。 我希望得到所有后代在祖先树中的后代地位<祖先地位的全部交易和全部花费。 有人可以帮忙吗? 目前,我为每个关系长度/状态=运行4次,因为有4个状态等级低于最高等级4。
查询:
select COUNT(*) as total, SUM(amt) as amount from transactions
left join card_holders_relations as t1 on transactions.chid = t1.descendant
left join card_holders as t2 on t2.id = t1.descendant
where t1.ancestor = '3'
AND t2.status = 0
AND t1.length = 4;
现在每次t2.status增加到不等于祖先状态,并且t1.length减少到1,因为长度= 0是他自己的祖先。
我的假设和方法是否正确?还是有更简单的方法?
链接地址: http://www.djcxy.com/p/93943.html