多对多关联查询mysql
时间: 2023-12-01 13:43:14 浏览: 153
多对多关联查询是指两个表之间存在多对多的关系,需要通过中间表来进行关联查询。下面是一个简单的多对多关联查询的例子:
假设有两个表:学生表(students)和课程表(courses),它们之间存在多对多的关系,需要通过中间表(student_courses)来进行关联查询。
首先,创建三个表:
```sql
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE courses (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE student_courses (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (course_id) REFERENCES courses(id)
);
```
然后,向三个表中插入一些数据:
```sql
INSERT INTO students VALUES (1, 'Tom');
INSERT INTO students VALUES (2, 'Jerry');
INSERT INTO students VALUES (3, 'Alice');
INSERT INTO courses VALUES (1, 'Math');
INSERT INTO courses VALUES (2, 'English');
INSERT INTO courses VALUES (3, 'Science');
INSERT INTO student_courses VALUES (1, 1);
INSERT INTO student_courses VALUES (1, 2);
INSERT INTO student_courses VALUES (2, 2);
INSERT INTO student_courses VALUES (3, 1);
INSERT INTO student_courses VALUES (3, 3);
```
最后,进行多对多关联查询:
```sql
SELECT students.name, courses.name
FROM students
JOIN student_courses ON students.id = student_courses.student_id
JOIN courses ON student_courses.course_id = courses.id;
```
以上查询语句将返回所有学生和他们所选的课程。
阅读全文