简体   繁体   English

从多对多关系中查询

[英]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? 我如何在MySql中查询“ John”的所有朋友? The schema is here. 模式在这里。

http://sqlfiddle.com/#!9/aeacd/1 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. 该查询的作用是在Student.idFriend.id_from.之间的联接表中选择将StudentFriendStudent联接,然后选择名称为"John"的条目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 http://sqlfiddle.com/#!9/aeacd/15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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