SQL中的各种连接介绍

准备工作

创建 表stu 和 表class

create table IF NOT EXISTS stu (
id bigint unsigned AUTO_INCREMENT comment '学号',
name varchar(50) not null comment '姓名',
age int unsigned not null comment '年龄',
class_id bigint unsigned  not null comment '班级号',
PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 comment '学生表';


create table IF NOT EXISTS class(
class_id bigint unsigned comment '班级号',
master varchar(50) not null comment '班主任',
number int unsigned not null comment '学生人数',
type varchar(20) not null comment '班级类型:文科、理科',
PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 comment '班级表';

插入内容

INSERT INTO stu(id, name, age, class_id)
values
(1, '李晓芳', 24, '201302'),
(2, '黄景瑜', 25, '201301'),
(3, '郭麒麟', 25, '201304'),
(4, '范丞丞', 25, '201307');

INSERT INTO class(class_id, master, number, type)
values
('201301', '付涛', 64, '理科'),
('201302', '李卫东', 72, '理科'),
('201304', '谭勇', 69, '文科'),
('201306', '刘淑兰', 65, '理科');

两张表如下:





1、内连接(等值连接),inner join on


(1)有on条件

select * from stu inner join class on stu.class_id = class.class_id;

内连接是左连接和右连接的交集。

(2)无on条件

相当于笛卡尔积

select * from stu inner join class;
或者
select * from stu, class;





2、全连接(全外连接、外连接),full join on


(1)有on条件

全连接是左连接和右连接的并集。

select * from stu full join class on stu.class_id = class.class_id; (MySQL不支持该写法,可以使用下面的union写法)
或者
select * from stu left join class on stu.class_id = class.class_id
union
select * from stu right join class on stu.class_id = class.class_id;

(2)无on连接

无on的全连接是笛卡尔积

select * from stu full join class;





3、左连接(左外连接)


select * from stu left join class on stu.class_id = class.class_id;





4、右连接(右外连接)

select * from stu right join class on stu.class_id = class.class_id;





5、等值连接

过滤条件为"="的连接

select * from stu, class where stu.class_id = class.class_id;





6、自然连接

自然连接是一种特殊的等值连接,它要求两个关系进行比较的分量必须是同名的属性组,并且在结果集中将重复属性列去掉。

自然连接自动带着比较的条件,不需要再加on条件。

select * from stu natural join class;





7、叉连接(交叉连接、笛卡尔积)


大概,MySQL实现的不带on条件的连接都等效于笛卡尔积。

但这些连接关系都来源于数学中的概念,从数学推导和实际应用来说,不带on条件的内连接、全连接没有意义。

上文写的不带on的内连接、外连接,只是说MySQL中实现了这回事,并不是有意义的分类,了解一下就行。

select * from stu cross join class;
或者
select * from stu, class;
或者
select * from stu join class;
或者
select * from stu inner join class;

参考

https://www.cnblogs.com/zeroingToOne/p/9575203.html

https://blog.csdn.net/qq_44625080/article/details/104063344

https://blog.csdn.net/u014454538/article/details/108948235

posted @ 2023-07-14 21:28  _lyl  阅读(47)  评论(0编辑  收藏  举报