103 . python高级------MySQl数据库的条件查询(5)

103 . python高级------MySQl数据库的条件查询(5)

python修炼第二十四天

2019年 4月 23日 晴

11.子查询

– 标量子查询: 子查询返回的结果是一个数据(一行一列)
– 列子查询: 返回的结果是一列(一列多行)
– 行子查询: 返回的结果是一行(一行多列)

– 查询出高于平均身高的信息(height)
– 得到平均身高

select avg(height) from students;
-- 大于平均 身高

select * from students where height > 172.076923;


select * from students where 
height > (select avg(height) from students);

– 查询学生的班级号能够对应的 学生名字

– 有多少 个班级

select name from classes;
select id from classes;

– 学生对应 的班级信息

select * from students where students.cls_id in(1,2);


select * from students where students.cls_id in(select id from classes);

–数据操作前的准备
–创建数据库表

create table areas(
aid int primary key,
atitle varchar(20),
pid int
);

–从sql文件中导入数据
– source 具体地址/areas.sql;

source xxx.sql;

–查询一共有多少个省

select * from areas where pid is null;

–例1:查询省的名称为“山西省”的所有城市

– 分两步
– 第一步查到山西 的编号

select * from areas where atitle = '山西省';
select aid from areas where atitle = '山西省';

– 第二步查到pid是山西 的编号

select * from areas where pid = '140000';

select * from areas where pid = (
	select aid from areas where atitle = '山西省'
);

select * from areas where pid = (
	select aid from areas where atitle = '杭州市'
);

– 自联

select * from areas as a1 inner join areas as a2 
on a1.pid = a2.aid  where a2.atitle = '杭州市'; 

–例2:查询市的名称为“广州市”的所有区县

select * from areas where pid = (
select aid from areas where atitle = '广州市'
);

	select * from areas as a1 inner join areas as a2 
on a1.pid = a2.aid  where a2.atitle = '上海'; 

猜你喜欢

转载自blog.csdn.net/qq_40455733/article/details/89503637
103