简体   繁体   中英

Query from many-to-many relationship

Student stores a list of student name and Friend stores relationship between students.

Create table Student (
id int NOT NULL AUTO_INCREMENT,
name varchar(35),
PRIMARY KEY (id)
);

insert into Student (name) values ('John');
insert into Student (name) values ('Kelly');
insert into Student (name) values ('Mary');

Create table Friend (
  id_from int NOT NULL REFERENCES Student(id),
  id_to int NOT NULL REFERENCES Student(id),
  PRIMARY KEY (id_from, id_to)
);

insert into Friend (id_from,id_to) values (1, 3);
insert into Friend (id_from,id_to) values (1, 2);
insert into Friend (id_from,id_to) values (3, 2);

How can I query all friends of "John", for example, in MySql? The schema is here.

http://sqlfiddle.com/#!9/aeacd/1

I have created a query. In general you can join tables with itself using the relation table. What the query does is join Student with Friend with Student and then selects the entries with "John" as name in the joined table between Student.id and Friend.id_from.

The query looks like this:

SELECT *
FROM Student as s1
INNER JOIN Friend as f1 on s1.id = f1.id_from
INNER JOIN Student as s2 on s2.id = f1.id_to
WHERE s1.name = "John";

you can try it out here:

http://sqlfiddle.com/#!9/aeacd/15

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM