Python | Mysql | 查询汇总

2019-08-12  本文已影响0人  CarryLili

前言:

承接上篇数据库基础增删改查操作。文章以students表为例

1,查询练习:

select * from students  ;

select 表别名.字段 .... from 表名 as 表别名;
例:可以给表起别名,查询表的name字段
select s.name from students as s; 

distinct 字段 去重 
例:性别去重  
select distinct gender from students ;

2,条件查询:

select .... from 表名 where …..
> < = >= <= !=
例:查询学生年龄大于18岁的所有学生信息
select * from students where age>18;

3,逻辑运算符:

and / between …and / or  /not 
例:查询年龄在18-28之间的学生信息
select * from students where age between 18 and 28;

4,模糊查询:

select * from students where 字段 like “ % __ _ ___"
例:查询姓名为 刘xx 的学生信息
select * from students where name like "刘__";

5,范围查询:

in(x, x, x) 查询不连续的范围

not in (x, x, x) 不在。。。范围内

between .. and .. 在一个连续的范围内

not between and  不在一个连续的范围内
例:查找年龄为18,28的学生信息,in 里面写什么值就是什么值,不连续
select * from students where age in (18,28);

6,空判断:

判空is null   not is null 不为空
例:查询身高为空的学生信息
select * from students where height is null;

7,排序:

order by  /  asc 从小到大 默认  /   desc 降序

例:查询年龄在18到33之间,且性别为男生的学生 以升序排序
select *  from students where age between 18 and 33 and gender = 1 order by age asc;

order by 后面可以加多个字段  身高从高到矮排序, 如果身高相同的情况下按照年龄从小到大排序   后面用逗号 隔开

8,分页:

limit (显示页面-1)*(显示个数),(显示个数)
例: 查询第五页,一页显示 2个
limit 8,2   (如果,limit跟排序,或者其他一些条件时,limit放在最后面)

9,聚合函数:

count /  max  /min / (avg=sum/count)  /sum  
四舍五入 round(123.23 , 1) 保留1位小数
例:计算男性平均身高,保留两位小数
select round(avg(height),2) from students where gender= 1; 

10,分组:

select 分组字段 from students 字段;
例:以性别分组
select gender from students group by gender;

分组一般会和聚合函数合用***(重要)
 select gender, count(*) from students group by gender;
group_concat(...)

 -- 查询同种性别中的姓名group_concat(name)
select gender, group_concat(name) from students group by gender;

11,with rollup 汇总的作用(了解)

例:查询班级每组性别的总数
select gender,count(*) from students group by gender with rollup;

12,连接查询

12.1内连接:
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;
12.2左链接:
select 字段 from 表1 left join 表2 on 表1.字段1 = 表2.字段2
例:学生表与班级表
select * from students as s left join classes as c on s.cls_id = c.id;
12.3右连接:
select 字段 from 表1 right join 表2 on 表1.字段1 = 表2.字段2
例:学生表与班级表
select * from students as s right join classes as c on s.cls_id = c.id;

13,子查询:

在一个select 语句中,嵌入了另外一个select 语句, 那么被嵌入的select 语句称之为子查询语句,外部那个select语句则称为主查询.

例:查询大于平均年龄的学生
select * from students where age > (select avg(age) from students);
上一篇 下一篇

猜你喜欢

热点阅读