内连接(INNER JOIN)是 SQL 中最常用的连接类型。它返回两个或多个表中具有匹配值的行。

内连接语法

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

例子

假设我们有两个表 employeesdepartments

  • employees 表包含员工信息和他们的部门ID:
employee_id name department_id
1 Alice 4
2 Bob 3
3 Charlie 4
  • departments 表包含部门信息和他们的部门ID:
department_id department_name
1 HR
2 IT
3 Marketing
4 Sales

如果我们想要找出所有员工和他们所在的部门名称,我们可以使用内连接:

SELECT employees.name, departments.department_name
FROM employees
INNER JOIN departments
ON employees.department_id = departments.department_id;

这将返回以下结果:

name department_name
Alice Sales
Bob Marketing
Charlie Sales

扩展阅读

想要了解更多关于 SQL 连接的知识,可以阅读SQL 连接教程

<center><img src="https://cloud-image.ullrai.com/q/SQL_Join/" alt="SQL Join Example"/></center>