33. SQL--inner join:内连接
1. 前言
inner join 是 sql 中最重要、最常用的表连接形式,只有当连接的两个或者多个表中都存在满足条件的记录时,才返回行。
sql inner join 子句将 table1 和 table2 中的每一条记录进行比较,以找到满足条件的所有记录,然后将每一对满足条件的记录的字段值,合并为一条新的结果行。
inner join 是默认的表连接方式。当不加任何修饰性的关键字,只写 join 时,默认就是 inner join 连接。
2. 语法
inner join 的基本语法如下:
select table1.column1, table2.column2...
from table1
inner join table2
on table1.common_column1 = table2.common_column2;
table1.common_column1 = table2.common_column2 是连接条件,只有满足此条件的记录才会合并为一行。
以上 SQL 语句将产生 table1 和 table2 的交集,只有 table1 和 table2 中匹配的行才被返回,如下图所示:
3. 示例
现在有如下所示的两个表,分别是客户表和订单表。
表1:customers 表
+----+----------+-----+-----------+----------+ | id | name | age | address | salary | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
表2:orders 表
+-----+---------------------+-------------+--------+ | oid | date | customer_id | amount | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+
现在,让我们使用 inner join 连接这两个表,如下所示:
sql> select id, name, amount, date
from customers
inner join orders
on customers.id = orders.customer_id;
执行结果:
+----+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +----+----------+--------+---------------------+ | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | +----+----------+--------+---------------------+
如果您不希望选取表的所有记录,也可以加上 WHERE 子句,如下所示:
sql> select id, name, amount, date
from customers
inner join orders
on customers.id = orders.customer_id;
where amount >1515
order by amount;
执行结果:
+----+----------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +----+----------+--------+---------------------+ | 2 | Khilan | 1560 | 2009-11-20 00:00:00 | | 4 | Chaitali | 2060 | 2008-05-20 00:00:00 | | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | +----+----------+--------+---------------------+