mysql sql select和跟随者/跟随者名称的内部联接

时间:2018-11-29 14:51:36

标签: mysql sql inner-join

我一直在努力想出一种方法,该方法如何选择所有关注者名称和每个关注者的关注者名称。我的表如下所示

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 |
+---------+---------+
| John    | Eve     |
| John    | Alice   |
| John    | Malorie |
| Alice   | John    |
| Alice   | Eve     |
| Eve     | Alice   |
+---------+---------+

1 个答案:

答案 0 :(得分:1)

您可以对某人使用两次join,一个人一个,而另一个人作为追随者的名字

    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