首先,建立两张表学生信息表(学生ID、学生姓名、学生性别)和学生成绩表(学生ID、学生成绩、成绩等级)
create table student_info(
student_id int(10),
student_name varchar(50),
student_sex varchar(10)
);
create table student_score(
student_id int(10),
student_score int(10),
student_grade varchar(50)
);
insert into student_info values(1,'小苍', '男'),(2,'小泽','女'),(3,'小天','男'),(4,'小加','男'),(5,'小吉','女');
insert into student_score values(1, 96,'优秀'),(2, 88, '良好'), (3, 60, '合格'), (6, 54, '不合格');
student_info表:
student_score表:
1.笛卡尔积
select info.*, score.* from student_info info, student_score score;
查询数量为两张表数量之积4*5 =20
像这种多表进行连接查询时没有任何条件,最终的结果是多表结果数量乘积的现象被称为笛卡尔积。
2.内连接
select info.*,score.* from student_info info inner join student_score score on info.student_id = score.student_id;
3.左外连接
概述:指将左表的所有记录与右表符合条件的记录,返回的结果除内连接的结果,还有左表不符合条件的记录,并在右表相应列中填NULL
select info.*,score.* from student_info info left join student_score score on info.student_id = score.student_id;
4.右外连接
概述:与左外连接相反,指将右表的所有记录与左表符合条件的记录,返回的结果除内连接的结果,还有右表不符合条件的记录,并在左表相应列中填NULL。
select info.* ,score.* from student_info info right join student_score score on info.student_id = score.student_id;
5.自连接
概述:指用表的别名实现表自身的连接。
select b.* from student_score a, student_score b where a.student_id = b.student_id and b.student_score > 80;