l连接查询可以实现多个表的查询
- 内连接查询
- 左连接查询
- 右连接查询
- 自连接查询
内连接查询
去交集
select 字段 from 表1 inner join 表2 on 表1.字段1 = 表2.字段2
select * from students as s inner join classes as c on s.cls_id = c.id;
desc students;
show create table students
alter table students add c_id; 学生表添加此字段 来和班级表进行连接使用
update students set c_id=2 where id in (1,3,5,7);
修改下学生表c_id=2, id为 1 3 5 7的学生
update students set c_id=1 where id in (2,4);
学生表
班级表
select * from students as s inner join classes as cls on s.c_id=cls.id;
2个表相同的值组成新表 students的c_id 和classes的id是一致的
左连接
写法 与之上面一致 改为 left join
意思是依据左表为主表,左表的数据都会查询出来,右表若无对应的数据则null
以左表为主根据条件查询右表数据,如果根据条件查询右表数据不存在使用null值填充
select * from students left join classes on students.c_id=classes.id;
右连接
与左连接相反的意思 用法一致
自连接
就是自己连接自己 ,条件查询一张表中具有相同数据的字段,
比如省和省内城市 假如山东省 id 1 那么旗下的所有市的c_id也是1存与一张表中
create table areas(
id varchar(30) not null primary key,
title varchar(30),
pid varchar(30)
);
执行sql文件给areas表导入数据:
source areas.sql;
select * from china as c inner join china as ch on c.Pid=ch.Id where ch.Name='北京市';
子查询
就是嵌套查询
例1. 查询大于平均年龄的学生:
select * from students where age > (select avg(age) from students);
例2. 查询学生在班的所有班级名字:
select name from classes where id in (select cls_id from students where cls_id is not null);
例3. 查找年龄最大,身高最高的学生:
select * from students where (age, height) = (select max(age), max(height) from students);