How to join multiple tables in MySQL?

In MySQL, JOIN statements can be used to combine multiple tables. Here are two common methods for joining multiple tables.

  1. INNER JOIN: connects rows from two or more tables that meet a specified condition. Syntax is as follows:
SELECT 列名
FROM 表格1
INNER JOIN 表格2 ON 表格1.列名 = 表格2.列名;

For example, connect two tables, table1 and table2, by joining them based on their id columns.

SELECT table1.id, table1.name, table2.address
FROM table1
INNER JOIN table2 ON table1.id = table2.id;
  1. LEFT JOIN: Returns all rows from the left table, even if there is no matching row in the right table. Syntax as follows:
SELECT 列名
FROM 表格1
LEFT JOIN 表格2 ON 表格1.列名 = 表格2.列名;

For instance, linking two tables table1 and table2, retrieve all rows from table1 along with the matching rows from table2.

SELECT table1.id, table1.name, table2.address
FROM table1
LEFT JOIN table2 ON table1.id = table2.id;

By using the methods mentioned above, it is possible to connect multiple tables in MySQL and achieve complex querying requirements.

Leave a Reply 0

Your email address will not be published. Required fields are marked *