MySQL表的内外连接

内外连接

1.熟悉表连接的几种方式
2.熟悉几种表连接的区别
3.掌握多表连接查询【重点】

什么是表连接?
表连接(JOIN)是在多个表之间通过一定的连接条件,使表之间发生关联,进而能使多个表之间获取数据。

在这里插入图片描述
【重点】内连接取交集
在这里插入图片描述
【重点】左连接,把没有成绩的也显示出来
在这里插入图片描述

表连接语法:
select table1.column,table2.column
from table1,table2
where table1.column=table2.column;
内连接取交集
select A.c1,B.c2
from A join B
on A.c3=B.c3
左连接
select A.c1,B.c2
from A left join B
on A.c3=B.c3
|---------------------------------------------------------------------------------------------------------------------

开始实操

我们只需要掌握内连接和左连接,想当于掌握了内外连接了,基本可以解决我们的
应用需求了。

创建学生表和分数表,插入数据
drop table if exists score;
drop table if exists student;

create table student(
	stu_no varchar(20) not null primary key comment '学号',
	name varchar(30) comment '姓名',
	address varchar(150) comment '地址'
);

insert into student(stu_no, name, address) values('2016001', '张三', '贵州贵阳');
insert into student(stu_no, name, address) values('2016002', '李芳', '陕西兴平');
insert into student(stu_no, name, address) values('2016003', '张晓燕', '江西南昌');

create table score(
	id int not null auto_increment primary key,
	course varchar(50) comment '科目',
	stu_no varchar(20) comment '学号',
	score int comment '分数',
	foreign key(stu_no) references student(stu_no)
);

insert into score(course, stu_no, score) values('计算机', '2016001', 99);
insert into score(course, stu_no, score) values('离散数学', '2016001', 85);
insert into score(course, stu_no, score) values('计算机', '2016002', 78);

mysql> select A.stu_no,A.name,B.course,B.score from student A join score B on A.stu_no=B.stu_no;
和下面的语句等价
mysql> select A.stu_no,A.name,B.course,B.score from student A,score B where A.stu_no=B.stu_no;

左连接,不管这个人有没有成绩,都把结果显示出来。
mysql> select A.stu_no,A.name,B.course,B.score from student A left join score B on A.stu_no=B.stu_no;

交叉连接,没有添加where连接条件,产生笛卡尔积,实际应用上没什么意义,应该避免
mysql> select A.stu_no,A.name,B.course,B.score from student A join score B
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值