美文网首页
python学习笔记-数据库06_连接查询

python学习笔记-数据库06_连接查询

作者: MR_詹 | 来源:发表于2020-11-12 23:06 被阅读0次

连接查询可以实现多表的查询,当查询的字段数据来自不同的表就可以使用连接查询来完成
连接查询可以分为:
内连接查询
左连接查询
右连接查询
自连接查询

内连接查询

查询两个表中符合条件的共有记录

内连接查询语法格式:
select 字段 from 表1 inner join 表2 on 表1.字段1 = 表2.字段2;
inner join: 就是内连接查询关键字
on : 就是连接查询条件

// 使用内连接查询学生表与班级表
select * from students as s inner join classes as c on s.cls_id = c.id;

学生表、班级表

左连接

以左表为主根据条件查询右表数据,如果根据条件查询右表数据不存在的使用null填充
(以左表数据的字段为主,比如下方列子的students表的c_id为主,那么students表中c_id的所有数据都会显示出来,包括右表classes没有的)
语句格式:
select 字段 from 表1 left join 表2 on 表1.字段1 = 表2.字段2;
备注:
表1 是 左表
表2 是 右表

// 使用左连接查询学生表与班级表
select * from students s left join classes s on s.c_id = c.id;

右连接

以右表为主根据条件查询左表数据,如果根据条件查询左表数据不存在使用null填充
语句格式:
select * from 表1 right join 表2 on 表1.字段1 = 表2.字段2;
备注:
表1 是 左表
表2 是 右表

自连接

左表和右表是同一个表,根据连接查询条件查询两个表中的数据。
比如:
select c.id , c.title, c.pid ,p.title from areas as c inner join areas as p on c.pid = p.id;
备注:
自链接查询就是吧一张表模拟成两张表,然后进行连表查询。这种情况少见

子查询

一个select语句中,嵌入了另外一个select语句,那么被嵌入的select语句称之为子查询语句,外部哪个select 语句则称为主查询
子查询是嵌入到主查询中的;
子查询是辅助主查询的,要么充当条件要么充当数据源
子查询是可以独立存在的语句,是一条完整的select语句

// 查询大于平均年龄的学生
select * from students where age > (select avg(age) from students);
n
// 查询学生在班的所有班级名字
select * from classes where id in (select c_id from students where c_id is not null);

// 查询年龄最大,升高最高的同学
select * from students where age = (select max(age) from students) and height = (select max(height) from students);
简写:
select * from studetns where (age,height) = (select max(age),max(height) from students);

补充:

执行sql文件给areas表导入数据:
source areas.sql

相关文章

网友评论

      本文标题:python学习笔记-数据库06_连接查询

      本文链接:https://www.haomeiwen.com/subject/hgxdbktx.html