级联查找成员资格引用的根 - PHP / MySQL查询

时间:2013-06-14 04:34:54

标签: php mysql cascade

我运行会员网站和mySQL数据库字段有ID,referid和rootid字段要知道 谁邀请谁和谁推荐谁

当新成员注册时,在新成员记录中,我在referid中写下她的邀请成员的id

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

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

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

如果我能以某种方式保存邀请和下线的树,那就更好了

困惑如何从这里开始

1 个答案:

答案 0 :(得分: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;

尝试一下