SQL中的几种连接

在SQL中,有n中连接,有时候闹的晕晕乎乎的,现在整理出来:
1、连接
select * from table1, table2;
select * from table1 cross join table2;
这种连接执行的结果是:
table1中的每一条记录都对应table2中的记录,像这样:
table1                     table2
1  ------- -1
2 ---------1
3---------1
1---------2
2---------2
3---------2

2、自连接
就是把一个表当两个表看,同表内进行连接
select a.name, b.name from table1 a, table1 b
where a.name = b.name;

3、内连接(inner join)
select a.name, b.name from table1 a inner join table2 b on a.name = b.name;
格式是:表1 inner join 表2 on 条件
等价于:
select a.name, b.name from table1 a, table2 b where a.name = b.name;

4、外连接(outer join)
允许限制一张表中的行,而不限制另外一张表中的行。
注意:外连接不一定非要有外键约束
4.1、左外连接(left outer join)
select * from table1 a left outer join table2 b on a.name = b.name;
列出table1中所有的项,table2中匹配不上的用NULL表示
结果:
idname
age
idnameage
1fred221fred22
2acea232acea23
3tom23
NULL
NULLNULL


4.2、右外连接(right outer join)
select * from table1 a right outer join table2 b on a.name = b.name;
和左外连接相反,列出table2中所有项,table1中不匹配的用NULL表示
结果:
idnameageidnameage
1fred221fred22
2acea232acea23
NULLNULLNULL4
mary
24

4.3、全连接(full join)
返回两个表中的匹配和不匹配的所有记录。
不是所有数据库都支持
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值