Home > Database > Mysql Tutorial > How to Join Multiple Tables in MySQL to Retrieve Related Data?

How to Join Multiple Tables in MySQL to Retrieve Related Data?

Linda Hamilton
Release: 2024-12-17 10:09:25
Original
869 people have browsed it

How to Join Multiple Tables in MySQL to Retrieve Related Data?

Joining Tables in MySQL

In MySQL, joining tables allows us to combine data from multiple tables based on shared columns. In this question, we aim to join three tables to retrieve specific information.

Joining Student, Course, and Bridge Tables

The given data includes three tables: Student (holds student names), Course (contains course names), and Bridge (connects student IDs to course IDs). To retrieve the desired result (listing student names with course names studied), you must use an inner join using ANSI syntax:

SELECT s.name AS Student, c.name AS Course
FROM student s
INNER JOIN bridge b ON s.id = b.sid
INNER JOIN course c ON b.cid = c.id
ORDER BY s.name;
Copy after login

This query will produce the expected result, showing each student's name and the courses they have studied.

Joining Employee and Manage Tables

For the second part of the question, we have two tables: Employee (holds employee names) and Manage (connects manager IDs to employee IDs). To retrieve the desired result (listing managers and their staff), you must use an inner join again:

SELECT e1.name AS Manager, e2.name AS Staff
FROM employee e1
INNER JOIN manage m ON e1.id = m.mid
INNER JOIN employee e2 ON m.eid = e2.id;
Copy after login

This query will provide the expected result, showing each manager's name and the names of their staff members.

The above is the detailed content of How to Join Multiple Tables in MySQL to Retrieve Related Data?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template