欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

sql server几种Join的区别测试方法

程序员文章站 2022-03-25 09:47:37
主要来介绍下inner join , full out join , cross join , left join , right join的区别。 inner join...

主要来介绍下inner join , full out join , cross join , left join , right join的区别。

inner join:筛选两边都有的记录
full out join:两边都筛选出来,匹配能匹配的,不能匹配的用null列出
cross join:列出两边所有组合,也称为笛卡尔集 a×b
left join:以左边的表为主表,列出主表所有记录,匹配能匹配的,不能匹配的用 null列出
right join:以右边的表为主表,列出主表所有记录,匹配能匹配的,不匹配的用null列出

下面来看代码:

创建测试表:

createtable consumers 
(
consumer_id intnotnull,
consumer_name varchar(10) notnull
)

createtable orders
(
consumer_id intnotnull, 
order_id varchar(10) notnull)

编测试数据

insert consumers values ( 1, 'aa')
insert consumers values ( 2, 'bb')
insert consumers values ( 3, 'cc')

insert orders values ( 2, 'o100001')
insert orders values ( 3, 'o100002')
insert orders values ( 3, 'o100003')
insert orders values ( 4, 'o100004')

测试

--inner join
--筛选两边都有的记录
select *
from orders o inner join consumers c
on o.consumer_id = c.consumer_id

--full out join
--两边都筛选出来,匹配能匹配的,不能匹配的用null列出
select *
from orders o full outer join consumers c
on o.consumer_id = c.consumer_id

--cross join
--列出两边所有组合,即笛卡尔集a×b
select *
from orders o cross join consumers c

--left join
--以左边的表为主表,列出主表所有记录,匹配能匹配的,不能匹配的用null列出
select * 
from consumers c left join orders o
on c .consumer_id = o .consumer_id

--right join
--以右边的表为主表,列出主表所有记录,匹配能匹配的,不能匹配的用null列出
select * 
from consumers c right join orders o
on c .consumer_id = o .consumer_id

ok了,具体的大家可以参考以前发布的文章。