连接查询 join (重要)
概念: 将多个表连接成为一个新的数据源, 这就是连接, 可以对新数据源进行查询.
连接前提: 根据关联字段才能进行连接(例如 学生表的class_id和班级表的class_id)
a. 要求查询出学生的名字,年龄,班级名称,教室号
select student.name,student.age,class.class_name,class.class_room
from student,class
where student.class_id=class.class_id;
给表取别名
select s.name,s.age,c.class_name,c.class_room
from student as s,class as c
where s.class_id=c.class_id;
非标准的连接查询
标准的连接查询使用, 表1 join 表2 on 连接条件
select s.name,s.age,c.class_name,c.class_room
from student as s join class as c
on s.class_id=c.class_id;
b. 所以标准的连接查询的语法
表1 join 表2 on 连接条件 ----- 构成一个新的数据源, 之后的语法和之前的查询语法一致
select s.name,s.age,c.class_name,c.class_room
from student as s
join class as c
on s.class_id=c.class_id where s.age>100;
c. 内连接
表1 join 表2 on 连接条件: 内连接指连接条件必须满足,才能查询出来
inner join / join : 内连接
select s.name,s.age,c.class_name,c.class_room
from student as s
inner join class as c
on s.class_id=c.class_id;
select s.name,s.age,c.class_name,c.class_room
from student as s
join class as c
on s.class_id=c.class_id;
d. 外连接
on 连接条件: 如果条件满足当然能查询出来, 当连接条件不满足的情况下也能查询出来. 这就是外连接.
外连接 无论连接条件是否连接成功,都能查询出来.....分不同情况
外连接分为两种情况: 左连接(left join,多) , 右连接(right join)
备注: 左右指的是 join 的左右
左连接(left join,多): 如果连接没有成功, 依然查询出join左边的数据
查出学生的名字,年龄,班级名称,教室号, 要求显示所有的学生信息
select s.name,s.age,c.class_name,c.class_room
from student as s
left join class as c
on s.class_id=c.class_id;
右连接(right join): 如果连接没有成功, 依然查询出join右边的数据
insert into class values(null,'H5精英班','B001');
查出学生的名字,年龄,班级名称,教室号, 要求显示所有的班级信息
select s.name,s.age,c.class_name,c.class_room
from student as s
right join class as c
on s.class_id=c.class_id;
e. 连接条件 on,using() 了解
如果连接条件的两个字段名一模一样,就可以使用using(字段)作为连接条件.
select s.name,s.age,c.class_name,c.class_room
from student as s
join class as c
on s.class_id=c.class_id;
修改为:
select s.name,s.age,c.class_name,c.class_room
from student as s
join class as c
using(class_id);
f. 案例
1. 可以同时连接多个表
2. 一个表可以同时被多次连接
球队表
create table team(
id int unsigned primary key auto_increment comment '主键id',
name varchar(20) not null comment '球队名'
);
insert into team(id,name) values(2,'拜仁'),(5,'慕尼黑');
比分表(比赛结果)
create table score(
hid int unsigned not null comment '主队id',
points varchar(10) not null default '0:0' comment '比分',
gid int unsigned not null comment '客队id'
);
insert into score(hid,points,gid) values(2,'3:0',5);
显示比赛结果, 要求显示队名
select ht.name,score.points,gt.name
from score
join team as ht on score.hid=ht.id
join team as gt on score.gid=gt.id;
sql join查询语句
最新推荐文章于 2024-01-17 15:58:40 发布