0

我运行会员站点,mySQL 数据库字段具有 ID、referid 和 rootid 字段,以了解谁邀请了谁以及谁推荐了谁

新会员注册时,在新会员记录中,我在referid中写了她的invitor会员id

反过来,A邀请B,B邀请C,C邀请D,D邀请E

E 有正确的字段引用为数据库中 D 的 id

我想要 E 的 rootid 字段中的 A 的 id,它是原始邀请人 这就像下线建设,但我无法用我的 3 个查询正确填充 rootid 字段,这些查询接受邀请人的引用并找到他们的 rootid 并设置在自己的 rootid 字段中

如果我能以某种方式保存邀请树和下线会更好

困惑如何从这里开始

4

1 回答 1

0

如果我没记错的话,这就是你所描述的......

CREATE TABLE members
(
  id INT UNSIGNED AUTO_INCREMENT NOT NULL,
  refer_id INT UNSIGNED,
  rootrefer_id INT UNSIGNED,
  name VARCHAR(100) NOT NULL,
  PRIMARY KEY(id)
);


/*Adam is an original member and was not reffered by anyone.*/
  INSERT INTO members (name) VALUES ('adam');

/*
Barbara is referred by Adam her id = 2
her refer_id, and rootrefer_id = 1
*/
  INSERT INTO members (name, refer_id, rootrefer_id) 
  VALUES('barbara', 1, 1);

/*
Cindy is referred by Barbara her id = 3, 
her refer_id = 2, her rootrefer_id = 1, just like Barbara
*/
  INSERT INTO members (name, refer_id, rootrefer_id)
  VALUES('cindy', 2, 1);

/*
Cindy in turn refers Dan, Dans id = 4
his refer_id = 3, and his rootrefer_id = 1
*/
  INSERT INTO members (name, refer_id, rootrefer_id)
  VALUES ('dan', 3, 1);

/*
Dan invites his pal Eddie, Eds id = 5
his refer_id = 4, and his rootrefer_id also = 1
*/
  INSERT INTO members (name, refer_id, rootrefer_id)
  VALUES ('eddie', 4, 1);

你可以这样查询:

#select original, non-refered members
#SELECT * FROM members WHERE refer_id IS NULL;

#select referred members
#SELECT * FROM members WHERE refer_id IS NOT NULL;

#select all referers and refered
SELECT 
  m1.id AS ref_id, 
  m1.name AS ref_name,
  m2.id AS id,
  m2.name AS name  
  FROM members m1
 JOIN members m2 ON m1.id=m2.refer_id;

#selct all root referers and refered
SELECT 
  m1.id AS root_id, 
  m1.name AS root_name,
  m2.id AS id,
  m2.name AS name  
  FROM members m1
 JOIN members m2 ON m1.id=m2.rootrefer_id;

#select all referers who are also referred, their referers and referred
SELECT
  mrr.id AS referrer_id,
  mrr.name AS referrer_name,
  m.id AS id,
  m.name AS name,
  mrd.id AS refered_id,
  mrd.name AS refered_name
  FROM members m
 JOIN members mrr ON mrr.id=m.refer_id
 JOIN members mrd ON m.id=mrd.refer_id;

试试看

于 2013-06-14T06:15:49.000 回答