表连接(内连接、外连接、自连接)
表连接(join)是多个表之间通过一定的连接条件,使表之间发生关联,进而能从多个表之间获取数据。
表连接语法
select table1.column,table2.column
from table1,table2
where table1.column1 = 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
#右连接
select A.c1,B.c2 from A right join B on A.c3 = B.c3
#全连接
select A.c1,B.c2 from A full join B on A.c3 = B.c3
交叉连接(cross join):没有用where子句的交叉连接将产生笛卡尔积,第一个表的行数乘以第二个表的行数等于笛卡尔积和结果集的大小。
创建学生表、成绩表
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 '地址'
)default charset=utf8;
insert into student(stu_no,name,address) values('20150901','Lau','湖北荆州');
insert into student(stu_no,name,address) values('20150902','张三','湖北武汉');
insert into student(stu_no,name,address) values('20150903','李四','天津');
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)
)default charset=utf8;
insert into score(course,stu_no,score) values('计算机','20150901',99);
insert into score(course,stu_no,score) values('离散数学','20150901',85);
insert into score(course,stu_no,score) values('计算机','20150902',78);
示例:
#内连接的三种表示方法
select A.stu_no,A.name,B.course,B.score
from student A
join score B on(A.stu_no = B.stu_no);
select A.stu_no,A.name,B.course,B.score
from student A
inner join score B on(A.stu_no = B.stu_no);
select A.stu_no,A.name,B.course,B.score
from student A,score B
where A.stu_no = B.stu_no;
#左连接
select A.stu_no,A.name,B.course,B.score
from student A
left join score B on(A.stu_no = B.stu_no);