我一直在努力想出一种方法,如何为每个跟随者选择所有跟随者的名字和跟随者的名字。我的桌子如下

CREATE TABLE person
(
    id int(10) auto_increment NOT NULL PRIMARY KEY,
    name varchar(100) NOT NULL DEFAULT '',
);

INSERT INTO person (name) VALUES ('John');
INSERT INTO person (name) VALUES ('Alice');
INSERT INTO person (name) VALUES ('Eve');
INSERT INTO person (name) VALUES ('Edgar');
INSERT INTO person (name) VALUES ('Malorie');

CREATE TABLE follows
(
    id int(10) NOT NULL DEFAULT '0',
    fid int(10) NOT NULL DEFAULT '0'
);

INSERT INTO follows (id,fid) VALUES (1,2);
INSERT INTO follows (id,fid) VALUES (1,3);
INSERT INTO follows (id,fid) VALUES (1,4);
INSERT INTO follows (id,fid) VALUES (2,1);
INSERT INTO follows (id,fid) VALUES (2,5);
INSERT INTO follows (id,fid) VALUES (3,2);
INSERT INTO follows (id,fid) VALUES (5,2);
INSERT INTO follows (id,fid) VALUES (5,1);

到目前为止,我已经提出了这样的声明,但显然它并没有按需要工作
SELECT person.name FROM person INNER JOIN follows ON (person.id = follows.id)

如何使查询在一个查询中同时选择folower和folowee名称?
预期的结果应该是这样的
+---------+---------+
| folower | folowee |
+---------+---------+
| John    | Eve     |
| John    | Alice   |
| John    | Malorie |
| Alice   | John    |
| Alice   | Eve     |
| Eve     | Alice   |
+---------+---------+

最佳答案

你可以使用join-on-person两次一个用于person,一个用于follower name

    SELECT person.name , follower.name
    FROM person
    INNER JOIN follows ON (person.id = follows.id)
    INNER JOIN person as follower on follows.fid = follower.id

10-08 09:31