MySQL 内连接、自然连接、外连接、Union

假设我们有两张表,分别是employees和customers。存储内容如下:

 

employees
employees
customers

 1. 内连接

select …… from 表1 inner join 表2 on 表1.A=表2.B

e.g:

select * from employees inner join customers on empID=custID;

2. 自然连接

select …… from 表1 natural join 表2 
等同于
select …… from 表1 inner join 表2 on 表1.A=表2.B

 e.g:

select * from employees natural join customers;

 自然连接会根据名称一样的属性自动链接,无需添加连接条件。而内连接可以自己指定属性。

3. 外连接

左外:
select …… from 表1 left join 表2 on 表1.A=表2.B
左外会完整保留表1

右外:
select …… from 表1 right join 表2 on 表1.A=表2.B
右外会完整保留表2

e.g:

select firstName, lastName, custID, customers.city from employees left join customers on employees.city=customers.city

 

select firstName, lastName, custID, customers.city from employees right join customers on employees.city=customers.city;

 与内连接对比:

select firstName, lastName, custID, customers.city from employees inner join customers on employees.city=customers.city;

 内连接会将不符合匹配条件的元组舍弃,而外连接会保留。

4. Union

将两次select查询得到的表结合。要求:1)列数相同。2)数据类型相同。3)顺序相同。

Union得到的元组们是无序的。

e.g:

SELECT firstName, lastName, custID, customers.city
FROM employees
LEFT JOIN customers
ON employees.city = customers.city
UNION
SELECT firstName, lastName, custID, customers.city
FROM employees
RIGHT JOIN customers
ON employees.city = customers.city;

 

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值