10_Mysql查询(重点-全流程)

在这里插入图片描述

一、数据的准备

1.1 创建数据库、数据表

-- 创建数据库
create database python_test charset=utf8;

-- 使用数据库
use python_test;

-- 显示使用的当前数据是哪个
select database();

-- 创建一个数据表
-- students表
create table students(
    id int unsigned primary key auto_increment not null,  -- 自动增长
    name varchar(20) default '',  -- 默认为空的字符串
    age tinyint unsigned default 0,
    height decimal(5,2),    -- 5位,默认2位小数
    gender enum('男','女','中性','保密') default '保密',
    cls_id int unsigned default 0,
    is_delete bit default 0
);

-- classes表
create table classes (
    id int unsigned auto_increment primary key not null,
    name varchar(30) not null
);

1.2 准备数据

-- 向students表中插入数据
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭于晏',29,185.00,1,1,0),
(0,'刘德华',59,175.00,1,2,1),
(0,'黄蓉',38,160.00,2,1,0),
(0,'凤姐',28,150.00,4,2,1),
(0,'王祖贤',18,172.00,2,1,1),
(0,'周杰伦',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'刘亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'静香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周杰',34,176.00,2,5,0);

-- 向classes表中插入数据
insert into classes values (0, "python_01期"), (0, "python_02期");

1.3 查询

1.3.1 查询所有字段

-- 查询所有字段
-- select * from 表名;
select * from students;
select * from classes;
select id, name from classes;

1.3.2 查询指定字段

-- 查询指定字段
-- select 列名1,列名2,... from 表名;
select name, age from students;

1.3.3 使用 as 给字段起别名

-- select 字段 as 名字.... from 表名;
select name as 姓名, age as 年龄 from students;

-- select 表名.字段 .... from 表名;
select students.name, students.age from students;

1.3.4 使用 as 给表起别名

-- select 别名.字段 .... from 表名 as 别名;
select students.name, students.age from students;
select s.name, s.age from students as s;

-- 失败的select students.name, students.age from students as s;

1.3.5 消除重复行

  • 在select后面列前使用distinct可以消除重复的行
-- distinct 字段
-- select distinct 列名1,列名2... from 表名;
select distinct gender from students;

1.3.6 总结

-- 查询所有字段
-- select * from 表名;
select * from students;
select * from classes;
select id, name from classes;

-- 查询指定字段
-- select 列名1,列名2,... from 表名;
select name, age from students;

-- 使用 as 给字段起别名
-- select 字段 as 名字.... from 表名;
select name as 姓名, age as 年龄 from students;

-- select 表名.字段 .... from 表名;
select students.name, students.age from students;


-- 可以通过 as 给表起别名
-- select 别名.字段 .... from 表名 as 别名;
select students.name, students.age from students;
select s.name, s.age from students as s;
-- 失败的select students.name, students.age from students as s;


-- 消除重复行
-- distinct 字段
select distinct gender from students;

二、条件查询 where

使用where子句对表中的数据筛选,结果为true的行会出现在结果集中

  • 语法如下:
-- select ... from 表名 where 条件;

select * from students where id=1;
  • where后面支持多种运算符,进行条件的处理
    • 比较运算符
    • 逻辑运算符
    • 模糊查询
    • 范围查询
    • 空判断

2.1 优先级

  • 优先级由高到低的顺序为:小括号,not,比较运算符,逻辑运算符
  • and比or先运算,如果同时出现并希望先算or,需要结合()使用

2.2 比较运算符

  • 等于: =
  • 大于: >
  • 大于等于: >=
  • 小于: <
  • 小于等于: <=
  • 不等于: != 或 <>
-- 查询大于18岁的信息
select * from students where age>18;
select id,name,gender from students where age>18;

-- 查询小于18岁的信息
select * from students where age<18;

-- 查询小于或者等于18岁的信息
select * from students where age<=18;

-- 查询年龄为18岁的所有学生的名字
select * from students where age=18;

2.3 逻辑运算符

  • and
  • or
  • not
-- and
-- 18到28之间的所以学生信息
select * from students where age>18 and age<28;
-- 失败select * from students where age>18 and <28;


-- 18岁以上的女性
select * from students where age>18 and gender="女";
select * from students where age>18 and gender=2;


-- or
-- 18以上或者身高查过180(包含)以上
select * from students where age>18 or height>=180;


-- not
-- 不在 18岁以上的女性 这个范围内的信息
-- select * from students where not age>18 and gender=2;
select * from students where not (age>18 and gender=2);

-- 年龄不是小于或者等于18 并且是女性
select * from students where (not age<=18) and gender=2;

2.4 模糊查询

  • like
  • %表示任意多个任意字符(0个,1个,多个)
  • _ 表示一个任意字符

2.4.1 like

-- 查询姓名中,以 "小" 开始的名字
select name from students where name="小";
select name from students where name like "小%";

-- 查询姓名中 有 "小" 所有的名字
select name from students where name like "%小%";

-- 查询有2个字的名字
select name from students where name like "__";

-- 查询有3个字的名字
select name from students where name like "___";

-- 查询至少有2个字的名字
select name from students where name like "__%";

2.4.2 rlike 正则

-- 查询以 周开始的姓名
select name from students where name rlike "^周.*";

-- 查询以 周开始,伦结尾的姓名
select name from students where name rlike "^周.*伦$";

2.5 范围查询

2.5.1 非连续范围

  • in 表示在一个非连续的范围内。
-- 查询编号是1或3或8的学生
select * from students where id=1 or id=3 or id=8;
select * from students where id in(1,3,8);

-- not in 不非连续的范围之内
-- 年龄不是 18、34岁之间的信息
select name,age from students where age not in (12, 18, 34);

2.5.2 连续范围

  • between … and …表示在一个连续的范围内
-- 查询编号为3至8的学生
select * from students where id between 3 and 8;

-- 查询编号是3至8的男生
select * from students where (id between 3 and 8) and gender=1;

-- not between ... and ...表示不在一个连续的范围内
-- 查询 年龄不在 在18到34之间的的信息
select * from students where age not between 18 and 34;
select * from students where not age between 18 and 34;
-- 失败的select * from students where age not (between 18 and 34);

2.6 空判断

  • 注意:null 与 ’ ’ 是不同的

2.6.1 判空 is null

-- 查询身高为空的信息
select * from students where height is null;
select * from students where height is NULL;
select * from students where height is Null;

2.6.2 判非空 is not null

-- 查询填写了身高的学生
select * from students where height is not null;

-- 查询填写了身高的男生
select * from students where height is not null and gender=1;

三、排序 order by

为了方便查看数据,可以对数据进行排序

语法:

select * from 表名 order by1 asc|desc [,2 asc|desc,...]

说明:

  • 将行数据按照列1进行排序,如果某些行列1的值相同时,则按照列2排序,以此类推
  • 默认按照列值从小到大排列(asc)
  • asc 从小到大排列,即升序
  • desc 从大到小排序,即降序
-- order by 字段
-- asc从小到大排列,即升序
-- desc从大到小排序,即降序

-- 查询年龄在18到34岁之间的男性,按照年龄从小到到排序
select * from students where (age between 18 and 34) and gender=1;
select * from students where (age between 18 and 34) and gender=1 order by age;
select * from students where (age between 18 and 34) and gender=1 order by age asc;


-- 查询年龄在18到34岁之间的女性,身高从高到矮排序
select * from students where (age between 18 and 34) and gender=2 order by height desc;


-- order by 多个字段
-- 查询年龄在18到34岁之间的女性,身高从高到矮排序, 如果身高相同的情况下按照年龄从小到大排序
select * from students where (age between 18 and 34) and gender=2 order by height desc,id desc;


-- 查询年龄在18到34岁之间的女性,先按身高从高到矮排序, 如果身高相同的情况下按照年龄从小到大排序,
-- 如果年龄也相同那么按照id从大到小排序
select * from students where (age between 18 and 34) and gender=2 order by height desc,age asc,id desc;


-- 按照年龄从小到大、身高从高到矮的排序
select * from students order by age asc, height desc;

四、聚合函数

为了快速得到统计数据,经常会用到如下5个聚合函数

4.1 总数 count()

  • count(*)表示计算总行数,括号中写星与列名,结果是相同的
-- 查询学生总数
select count(*) from students;

-- 查询男性有多少人,女性有多少人
select * from students where gender=1;
select count(*) from students where gender=1;
select count(*) as 男性人数 from students where gender=1;
select count(*) as 女性人数 from students where gender=2;

4.2 最大值 max()

  • max(列)表示求此列的最大值
-- 查询女生的编号最大值
select max(id) from students where gender=2;

-- 查询最大的年龄
select max(age) from students;

4.3 最小值 min()

  • min(列)表示求此列的最小值

例3:查询未删除的学生最小编号

-- 查询未删除的学生最小编号
select min(id) from students where is_delete=0;

4.4 求和 sum()

  • sum(列)表示求此列的和
-- 查询男生的总年龄
select sum(age) from students where gender=1;

-- 查询男生平均年龄
select sum(age)/count(*) from students where gender=1;

4.5 平均值 avg()

  • avg(列)表示求此列的平均值
-- 查询未删除女生的编号平均值
select avg(id) from students where is_delete=0 and gender=2;

4.6 四舍五入 round()

  • 四舍五入: round(123.23 , 1) 保留1位小数
-- 四舍五入 round(123.23 , 1) 保留1位小数
-- 计算所有人的平均年龄,保留2位小数
select round(sum(age)/count(*), 2) from students;
select round(sum(age)/count(*), 3) from students;

-- 计算男性的平均身高 保留2位小数
select round(avg(height), 2) from students where gender=1;
-- 失败select name, round(avg(height), 2) from students where gender=1;

五、分组 group by

5.1 group by

  1. group by的含义:将查询结果按照1个或多个字段进行分组,字段值相同的为一组
  2. group by可用于单个字段分组,也可用于多个字段分组
select * from students;
+----+-----------+------+--------+--------+--------+-----------+
| id | name      | age  | height | gender | cls_id | is_delete |
+----+-----------+------+--------+--------+--------+-----------+
|  1 | 小明      |   18 | 180.00 ||      1 |           |
|  2 | 小月月    |   18 | 180.00 ||      2 |          |
|  3 | 彭于晏    |   29 | 185.00 ||      1 |           |
|  4 | 刘德华    |   59 | 175.00 ||      2 |          |
|  5 | 黄蓉      |   38 | 160.00 ||      1 |           |
|  6 | 凤姐      |   28 | 150.00 | 保密   |      2 |          |
|  7 | 王祖贤    |   18 | 172.00 ||      1 |          |
|  8 | 周杰伦    |   36 |   NULL ||      1 |           |
|  9 | 程坤      |   27 | 181.00 ||      2 |           |
| 10 | 刘亦菲    |   25 | 166.00 ||      2 |           |
| 11 | 金星      |   33 | 162.00 | 中性   |      3 |          |
| 12 | 静香      |   12 | 180.00 ||      4 |           |
| 13 | 周杰      |   34 | 176.00 ||      5 |           |
| 14 | 郭靖      |   12 | 170.00 ||      4 |           |
+----+-----------+------+--------+--------+--------+-----------+

-- 按照性别分组,查询所有的性别
select gender from students group by gender;
+--------+
| gender |
+--------+
||
||
| 中性   |
| 保密   |
+--------+

根据gender字段来分组,gender字段的全部值有4个’男’,‘女’,‘中性’,‘保密’,所以分为了4组 当group by单独使用时,只显示出每组的第一条记录, 所以group by单独使用时的实际意义不大

5.2 group by + group_concat()

  1. group_concat(字段名)可以作为一个输出字段来使用,
  2. 表示分组之后,根据分组结果,使用group_concat() 来放置每一组的某字段的值的集合
select gender,group_concat(name) from students group by gender;
+--------+-----------------------------------------------------------+
| gender | group_concat(name)                                        |
+--------+-----------------------------------------------------------+
|| 彭于晏,刘德华,周杰伦,程坤,郭靖                                 |
|| 小明,小月月,黄蓉,王祖贤,刘亦菲,静香,周杰                        |
| 中性   | 金星                                                       |
| 保密   | 凤姐                                                       |
+--------+-----------------------------------------------------------+


select gender,group_concat(id) from students group by gender;
+--------+------------------+
| gender | group_concat(id) |
+--------+------------------+
|| 3,4,8,9,14       |
|| 1,2,5,7,10,12,13 |
| 中性   | 11               |
| 保密   | 6                |
+--------+------------------+

-- 计算男性的人数
select gender,count(*) from students where gender=1 group by gender;

5.3 group by + 聚合函数

  1. 通过group_concat()的启发,我们既然可以统计出每个分组的某字段的值的集合,那么我们也可以通过聚合函数来对这个值的集合做一些操作
-- 计算男性的人数
select gender,group_concat(name, "_", age, " ", id) from students where gender=1 group by gender;


select gender,group_concat(age) from students group by gender;
+--------+----------------------+
| gender | group_concat(age)    |
+--------+----------------------+
|| 29,59,36,27,12       |
|| 18,18,38,18,25,12,34 |
| 中性   | 33                   |
| 保密   | 28                   |
+--------+----------------------+


-- 分别统计性别为男/女的人年龄平均值
select gender,avg(age) from students group by gender;
+--------+----------+
| gender | avg(age) |
+--------+----------+
||  32.6000 |
||  23.2857 |
| 中性   |  33.0000 |
| 保密   |  28.0000 |
+--------+----------+

-- 分别统计性别为男/女的人的个数
select gender,count(*) from students group by gender;
+--------+----------+
| gender | count(*) |
+--------+----------+
||        5 |
||        7 |
| 中性   |        1 |
| 保密   |        1 |
+--------+----------+

5.4 group by + having

  1. having 条件表达式:用来分组查询后指定一些条件来输出查询结果
  2. having作用和where一样,但having只能用于group by
select gender,count(*) from students group by gender having count(*)>2;
+--------+----------+
| gender | count(*) |
+--------+----------+
||        5 |
||        7 |
+--------+----------+

-- 查询平均年龄超过30岁的性别,以及姓名。
select gender, group_concat(name),avg(age) from students group by gender having avg(age)>30;

-- 查询每种性别中的人数多于2个的信息
select gender, group_concat(name) from students group by gender having count(*)>2;

5.5 group by + with rollup

  1. with rollup的作用是:在最后新增一行,来记录当前列里所有记录的总和
select gender,count(*) from students group by gender with rollup;
+--------+----------+
| gender | count(*) |
+--------+----------+
||        5 |
||        7 |
| 中性   |        1 |
| 保密   |        1 |
| NULL   |       14 |
+--------+----------+


select gender,group_concat(age) from students group by gender with rollup;
+--------+-------------------------------------------+
| gender | group_concat(age)                         |
+--------+-------------------------------------------+
|| 29,59,36,27,12                            |
|| 18,18,38,18,25,12,34                      |
| 中性   | 33                                        |
| 保密   | 28                                        |
| NULL   | 29,59,36,27,12,18,18,38,18,25,12,34,33,28 |
+--------+-------------------------------------------+

六、分页

当数据量过大时,在一页中查看数据是一件非常麻烦的事情

语法

select * from 表名 limit start,count

说明

  • 从start开始,获取count条数据
-- 查询前3行男生信息
select * from students where gender=1 limit 0,3;


-- 限制查询出来的数据个数,出现2行
select * from students where gender=1 limit 2;

-- 查询前5个数据,从0位置开始,获取5条数据
select * from students limit 0, 5;

-- 查询id6-10(包含)的书序,共5条数据
select * from students limit 5, 5;


-- 每页显示2个,第1个页面
select * from students limit 0,2;

-- 每页显示2个,第2个页面
select * from students limit 2,2;

-- 每页显示2个,第3个页面
select * from students limit 4,2;

-- 每页显示2个,第4个页面
select * from students limit 6,2; -- -----> limit (第N页-1)*每个的个数, 每页的个数;

-- 每页显示2个,显示第6页的信息, 按照年龄从小到大排序
-- 失败select * from students limit 2*(6-1),2;
-- 失败select * from students limit 10,2 order by age asc;
select * from students order by age asc limit 10,2;

select * from students where gender=2 order by height desc limit 0,2;

示例:分页

  • 已知:每页显示m条数据,当前显示第n页
  • 求总页数:此段逻辑后面会在python中实现
    • 查询总条数p1
    • 使用p1除以m得到p2
    • 如果整除则p2为总数页
    • 如果不整除则p2+1为总页数
  • 求第n页的数据
select * from students where is_delete=0 limit (n-1)*m,m

七、连接查询(多表操作)

当查询结果的列来源于多张表时,需要将多张表连接成一个大的数据集,再选择合适的列返回

mysql支持三种类型的连接查询,分别为:

  • 内连接查询:查询的结果为两个表匹配到的数据。(取交集)

  • 左连接查询:查询的结果为两个表匹配到的数据,左表特有的数据,对于右表中不存在的数据使用null填充。

  • 右连接查询:查询的结果为两个表匹配到的数据,右表特有的数据,对于左表中不存在的数据使用null填充。

语法

select * from1 innerleftright join2 on1.=2.

7.1 inner join … on

-- select ... from 表A inner join 表B;
select * from students inner join classes;

-- 查询 有能够对应班级的学生以及班级信息
select * from students inner join classes on students.cls_id=classes.id;

-- 按照要求显示姓名、班级
select students.*, classes.name from students inner join classes on students.cls_id=classes.id;
select students.name, classes.name from students inner join classes on students.cls_id=classes.id;

-- 给数据表起名字
select s.name, c.name from students as s inner join classes as c on s.cls_id=c.id;

-- 查询 有能够对应班级的学生以及班级信息,显示学生的所有信息,只显示班级名称
select s.*, c.name from students as s inner join classes as c on s.cls_id=c.id;

-- 在以上的查询中,将班级姓名显示在第1列
select c.name, s.* from students as s inner join classes as c on s.cls_id=c.id;

-- 查询 有能够对应班级的学生以及班级信息, 按照班级进行排序
-- select c.xxx s.xxx from student as s inner join clssses as c on .... order by ....;
select c.name, s.* from students as s inner join classes as c on s.cls_id=c.id order by c.name;

-- 当同一个班级的时候,按照学生的id进行从小到大排序
select c.name, s.* from students as s inner join classes as c on s.cls_id=c.id order by c.name,s.id;

7.2 left join … on

-- 查询每位学生对应的班级信息
select * from students as s left join classes as c on s.cls_id=c.id;

-- 查询没有对应班级信息的学生
-- select ... from xxx as s left join xxx as c on..... where .....
-- select ... from xxx as s left join xxx as c on..... having .....
select * from students as s left join classes as c on s.cls_id=c.id having c.id is null;
select * from students as s left join classes as c on s.cls_id=c.id where c.id is null;

7.3 right join… on

-- 将数据表名字互换位置,用left join完成
select * from students as s right join classes as c on s.cls_id = c.id;

八、自关联

  • 设计省信息的表结构provinces
    • id
    • ptitle
  • 设计市信息的表结构citys
    • id
    • ctitle
    • proid
  • citys表的proid表示城市所属的省,对应着provinces表的id值

问题:

能不能将两个表合成一张表呢?

思考:

观察两张表发现,citys表比provinces表多一个列proid,其它列的类型都是一样的

意义:

存储的都是地区信息,而且每种信息的数据量有限,没必要增加一个新表,或者将来还要存储区、乡镇信息,都增加新表的开销太大

答案:

定义表areas,结构如下

  • id
  • atitle
  • pid

说明:

  • 因为省没有所属的省份,所以可以填写为null
  • 城市所属的省份pid,填写省所对应的编号id
  • 这就是自关联,表中的某一列,关联了这个表中的另外一列,但是它们的业务逻辑含义是不一样的,城市信息的pid引用的是省信息的id
  • 在这个表中,结构不变,可以添加区县、乡镇街道、村社区等信息

创建areas表的语句如下:

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

8.1 导入数据(重点)

  • 从sql文件中导入数据,一定要在有文件的路径下,启动mysql,并且在创建的表下,导入数据
source areas.sql;

8.2 练习

-- 查询一共有多少个省
select count(*) from areas where pid is null;


-- 查询省的名称为“山西省”的所有城市
select city.* from areas as city
inner join areas as province on city.pid=province.aid
where province.atitle='山西省';


-- 查询市的名称为“广州市”的所有区县
select dis.* from areas as dis
inner join areas as city on city.aid=dis.pid
where city.atitle='广州市';


-- 省级联动 url:http://demo.lanrenzhijia.com/2014/city0605/

-- 查询所有省份
select * from areas where pid is null;

-- 查询出山东省有哪些市
select * from areas as province inner join areas as city on city.pid=province.aid having province.atitle="山东省";
select province.atitle, city.atitle from areas as province inner join areas as city on city.pid=province.aid having province.atitle="山东省";

-- 查询出青岛市有哪些县城
select province.atitle, city.atitle from areas as province inner join areas as city on city.pid=province.aid having province.atitle="青岛市";

九、子查询

子查询

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

主查询

  • 主要查询的对象,第一条 select 语句

主查询和子查询的关系

  • 子查询是嵌入到主查询中
  • 子查询是辅助主查询的,要么充当条件,要么充当数据源
  • 子查询是可以独立存在的语句,是一条完整的 select 语句

9.1 子查询中特定关键字使用

  • in 范围
    • 格式: 主查询 where 条件 in (列子查询)

9.2 子查询分类

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

9.2.1 标量子查询

  1. 查询班级学生平均年龄
  2. 查询大于平均年龄的学生
-- 查询班级学生的平均身高
select * from students where age > (select avg(age) from students);

9.2.2 列级子查询

  • 查询还有学生在班的所有班级名字
    1. 找出学生表中所有的班级 id
    2. 找出班级表中对应的名字
select name from classes where id in (select cls_id from students);

9.2.3 行级子查询

  • 需求: 查找班级年龄最大,身高最高的学生
  • 行元素: 将多个字段合成一个行元素,在行级子查询中会使用到行元素
select * from students where (height,age) = (select max(height),max(age) from students);

十、查询的完整格式

SELECT select_expr [,select_expr,...] [      
      FROM tb_name
      [WHERE 条件判断]
      [GROUP BY {col_name | postion} [ASC | DESC], ...] 
      [HAVING WHERE 条件判断]
      [ORDER BY {col_name|expr|postion} [ASC | DESC], ...]
      [ LIMIT {[offset,]rowcount | row_count OFFSET offset}]
]
  • 完整的select语句
select distinct *
from 表名
where ....
group by ... having ...
order by ...
limit start,count
  • 执行顺序为:
    • from 表名
    • where …
    • group by …
    • select distinct *
    • having …
    • order by …
    • limit start,count
  • 实际使用中,只是语句中某些部分的组合,而不是全部
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少云清

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值