如果我没记错的话,这就是你所描述的......
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;
试试看