mysql多对多关联查询
时间: 2023-10-15 11:31:16 浏览: 86
对于MySQL多对多关联查询,你可以通过中间表来实现。以下是一个示例:
假设你有两个表:'students'和'courses'。一个学生可以选择多门课程,一门课程也可以被多个学生选择。你可以创建一个中间表'student_courses'来建立关联。
首先,创建三个表:
```sql
CREATE TABLE students (
student_id INT PRIMARY KEY,
student_name VARCHAR(50)
);
CREATE TABLE courses (
course_id INT PRIMARY KEY,
course_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(student_id),
FOREIGN KEY (course_id) REFERENCES courses(course_id)
);
```
然后,插入一些数据到这些表中:
```sql
INSERT INTO students (student_id, student_name) VALUES (1, 'Alice');
INSERT INTO students (student_id, student_name) VALUES (2, 'Bob');
INSERT INTO students (student_id, student_name) VALUES (3, 'Charlie');
INSERT INTO courses (course_id, course_name) VALUES (101, 'Math');
INSERT INTO courses (course_id, course_name) VALUES (102, 'Science');
INSERT INTO courses (course_id, course_name) VALUES (103, 'History');
INSERT INTO student_courses (student_id, course_id) VALUES (1, 101);
INSERT INTO student_courses (student_id, course_id) VALUES (1, 102);
INSERT INTO student_courses (student_id, course_id) VALUES (2, 101);
INSERT INTO student_courses (student_id, course_id) VALUES (3, 103);
```
现在,你可以使用多对多关联查询来获取学生选择的课程或课程被哪些学生选择了。
获取学生选择的课程:
```sql
SELECT students.student_name, courses.course_name
FROM students
JOIN student_courses ON students.student_id = student_courses.student_id
JOIN courses ON student_courses.course_id = courses.course_id
WHERE students.student_name = 'Alice';
```
获取选择了某门课程的学生:
```sql
SELECT students.student_name, courses.course_name
FROM students
JOIN student_courses ON students.student_id = student_courses.student_id
JOIN courses ON student_courses.course_id = courses.course_id
WHERE courses.course_name = 'Math';
```
希望这个例子能帮助你理解MySQL中的多对多关联查询。
阅读全文