SQL INNER JOIN学习笔记

什么是SQL INNER JOIN?

在SQL中,INNER JOIN是一种用于将两个或多个表中的行结合起来的方法。JOIN操作根据行之间的某些条件将两个表中的数据合并在一起,形成一个新的表格。

INNER JOIN指的是只返回两个表中匹配的行。即只有左表和右表中都有的记录才会被返回。

INNER JOIN的语法

内部联接的语法如下所示:

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

在这里,table1table2表示要联接的表格的名称。column_name列出了要从每个表中选择的列名。ON后面的条件指定了匹配行的条件。

INNER JOIN的实例

现在,我们使用两个具有相似列(country)的表进行演示:“employees”和“customers”。

employees表

employee_id first_name last_name birth_date country
1 John Doe 1990-01-01 USA
2 Jane Smith 1992-03-01 UK
3 Phil Brown 1987-05-11 USA
4 Mary Johnson 1995-07-15 USA

customers表

customer_id customer_name contact_name country
1 Alfreds Futterkiste Maria Anders Germany
2 Ana Trujillo Emparedados Ana Trujillo Mexico
3 Antonio Moreno Taquería Antonio Moreno Mexico
4 Around the Horn Thomas Hardy UK

下面的SQL语句使用 INNER JOIN 操作选择两个表中 country 字段相等的记录。

sqlCopy Code
SELECT employees.first_name, employees.last_name, customers.customer_name FROM employees INNER JOIN customers ON employees.country = customers.country;

输出为:

first_name last_name customer_name
John Doe Alfreds Futterkiste
Phil Brown Alfreds Futterkiste
Jane Smith Around the Horn
John Doe Around the Horn
Mary Johnson Around the Horn
Phil Brown Around the Horn
Ana Trujillo Ana Trujillo Emparedados
Antonio Moreno Antonio Moreno Taquería
Ana Trujillo Antonio Moreno Taquería

在上面的输出中,我们可以看到,只有左表和右表中都有相同country的行才被返回了。在这种情况下,只有来自employees表的三个员工(John Doe、Phil Brown和Jane Smith)和来自customers表的三个客户(Alfreds Futterkiste、Around the Horn和Antonio Moreno Taquería)拥有相同的国家(即USAUK),因此只有这些行被返回。