程序员社区

MySQL系列教程 --- 71、MySQL 中的 连接查询

MySQL JOINS 与 SELECT 语句一起使用。它用于从多个表中检索数据。只要您需要从两个或多个表中获取记录,就会执行此操作。

MySQL连接分为三种类型:

  • MySQL INNER JOIN(或有时称为简单连接)
  • MySQL LEFT OUTER JOIN(或有时称为LEFT JOIN)
  • MySQL RIGHT OUTER JOIN(或有时称为 RIGHT JOIN)

MySQL 内连接(简单连接)

在MySQL的INNER JOIN用于返回从多个表,其中的连接条件是满足的所有行。它是最常见的连接类型。

句法:

SELECT columns  
FROM table1   
INNER JOIN table2  
ON table1.column = table2.column;  

图像表示:

file

让我们举个例子:

考虑两个表“officers”和“students”,具有以下数据。

file

执行以下查询:

SELECT officers.officer_name, officers.address, students.course_name  
FROM officers   
INNER JOIN students  
ON officers.officer_id = students.student_id;   

输出:

file

MySQL 左外连接

LEFT OUTER JOIN 返回 ON 条件中指定的左侧表中的所有行,并且仅返回满足连接条件的其他表中的那些行。

句法:

SELECT columns  
FROM table1  
LEFT [OUTER] JOIN table2  
ON table1.column = table2.column;  

图像表示:

file

让我们举个例子:

考虑两个表“官员”和“学生”,具有以下数据。

file

执行以下查询:

SELECT  officers.officer_name, officers.address, students.course_name  
FROM officers  
LEFT JOIN students  
ON officers.officer_id = students.student_id;  

输出:

file

MySQL 右外连接

MySQL 右外连接返回 ON 条件中指定的 RIGHT-hand 表中的所有行,并且仅返回满足连接条件的其他表中的那些行。

句法:

SELECT columns  
FROM table1  
RIGHT [OUTER] JOIN table2  
ON table1.column = table2.column;  

图像表示:

file

让我们举个例子:

考虑两个表“officers”和“students”,具有以下数据。

file

执行以下查询:

SELECT officers.officer_name, officers.address, students.course_name, students.student_name  
FROM officers  
RIGHT JOIN students  
ON officers.officer_id = students.student_id;  

输出:

file

赞(0) 打赏
未经允许不得转载:IDEA激活码 » MySQL系列教程 --- 71、MySQL 中的 连接查询

一个分享Java & Python知识的社区