How to perform multi-table query in MySQL?
In database queries, multi-table queries are a common requirement. Through multi-table query, we can connect and correlate data in multiple tables to get more accurate and comprehensive query results. MySQL provides a variety of ways to perform multi-table queries, including using JOIN statements, subqueries, and union queries. This article will introduce how to perform multi-table queries in MySQL, with code examples.
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
The above query will return records from the Orders table and Customers table that meet the connection conditions. The query results include the OrderID, CustomerName and OrderDate fields.
SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
The above query will return all Customers table records and match Orders table records that meet the connection conditions. The query results include the CustomerName and OrderID fields.
SELECT Orders.OrderID, Customers.CustomerName FROM Orders RIGHT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
The above query will return all Orders table records and match the Customers table records that meet the connection conditions. The query results include the OrderID and CustomerName fields.
SELECT Customers.CustomerName, Orders.OrderID FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID UNION SELECT Customers.CustomerName, Orders.OrderID FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID WHERE Customers.CustomerID IS NULL;
The above query will return all Customers table records and Orders table records that meet the connection conditions, and display records that do not meet the conditions as NULL.
Multi-table query is one of the important skills in database query. By rationally using connection operators and conditions, we can perform related queries on multiple tables according to actual needs and obtain accurate and comprehensive results. I hope this article will help you understand how to perform multi-table queries in MySQL.
The above is the detailed content of How to perform multi-table query in MySQL?. For more information, please follow other related articles on the PHP Chinese website!