follower/followee名称的mysql选择和内部连接

fsi0uk1n  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(239)

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

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)

如何在一个查询中同时选择follower和folowee的名字?
预期的结果应该是这样的

+---------+---------+
| folower | folowee |
+---------+---------+
| John    | Eve     |
| John    | Alice   |
| John    | Malorie |
| Alice   | John    |
| Alice   | Eve     |
| Eve     | Alice   |
+---------+---------+
kcrjzv8t

kcrjzv8t1#

你可以在person上使用join两次一次表示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

相关问题