文章目录

  • 1、概述
  • 2、where 条件查询
  • 3、group by 分组查询
    • 常用的聚合函数
    • group by + 聚合函数
  • 4、having筛选
  • 5、order by 排序
  • 6、limit 分页

1、概述

在MySQL的查询中,select主要有5中子句类型,主要包括

  • where 条件查询
  • group by 分组查询
  • having 筛选
  • order by 排序
  • limit 分页

准备演示的表结构及示例数据

CREATE TABLE "department" ("did" int(11) NOT NULL AUTO_INCREMENT,"dname" varchar(100) NOT NULL,"description" varchar(200) DEFAULT NULL,"manager_id" int(11) DEFAULT NULL,PRIMARY KEY ("did")
) ENGINE=InnoDB DEFAULT  CHARSET=utf8mb4;CREATE TABLE "employee" ("eid" int(11) NOT NULL AUTO_INCREMENT,"ename" varchar(100) NOT NULL,"gender" char(1) NOT NULL DEFAULT '男',"card_id" char(18) DEFAULT NULL,"‘mid‘" int(11) DEFAULT NULL,"dept_id" int(11) DEFAULT NULL,PRIMARY KEY ("eid"),UNIQUE KEY "card_id" ("card_id"),KEY "dept_id" ("dept_id"),CONSTRAINT "employee_ibfk_1" FOREIGN KEY ("dept_id") REFERENCES "department" ("did")
) ENGINE=InnoDB DEFAULT  CHARSET=utf8mb4;CREATE TABLE "salary" ("eid" int(11) NOT NULL,"basic_salary" decimal(10,2) DEFAULT NULL,"performance_salary" decimal(10,2) DEFAULT NULL,PRIMARY KEY ("eid"),CONSTRAINT "salary_ibfk_1" FOREIGN KEY ("eid") REFERENCES "employee" ("eid")
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;INSERT INTO `department`(dname,description) VALUES ( '研发部', '业务平台研发');
INSERT INTO `department` (dname,description) VALUES ( '市场部', '市场推广');
INSERT INTO `department` (dname,description) VALUES ( '财务部', '财务管理');INSERT INTO `employee` (ename,gender,card_id,‘mid‘,dept_id) VALUES ('张三', '男', '123456789012345678', null, '1');
INSERT INTO `employee` (ename,gender,card_id,‘mid‘,dept_id) VALUES ('李四', '女', '123456789012345665', null, '2');
INSERT INTO `employee` (ename,gender,card_id,‘mid‘,dept_id) VALUES ('赵柳', '男', '123456789012235678', '2', '2');
INSERT INTO `employee` (ename,gender,card_id,‘mid‘,dept_id) VALUES ('王五', '男', '123456789012115678', '1', '1');
INSERT INTO `employee` (ename,gender,card_id,‘mid‘,dept_id) VALUES ('谷雨', '男', '123456789012115978', '1', '1');INSERT INTO `salary` VALUES ('1', '12000.00', '6000.00');
INSERT INTO `salary` VALUES ('2', '9000.00', '8000.00');
INSERT INTO `salary` VALUES ('3', '11000.00', '5500.00');
INSERT INTO `salary` VALUES ('4', '5800.00', '7800.00');

2、where 条件查询

where :从原表的记录中进行筛选

3、group by 分组查询

在实际的应用中,需要进行一些汇总操作,例如:统计整个公司的人数或者统计每一个部门的人数等。

常用的聚合函数

函数名称 函数说明
AVG([DISTINCT] expr) 返回expr的平均值
COUNT([DISTINCT] expr) 返回expr的非NULL值的数目
MIN([DISTINCT] expr) 返回expr的最小值
MAX([DISTINCT] expr) 返回expr的最大值
SUM([DISTINCT] expr) 返回expr的平均值
#聚合函数
#AVG(【DISTINCT】 expr) 返回 expr 的平均值
mysql> select avg(basic_salary) from salary;
+-------------------+
| avg(basic_salary) |
+-------------------+
| 9450.000000       |
+-------------------+
1 row in set#COUNT(【DISTINCT】 expr)返回 expr 的非 NULL 值的数目
#统计员工总人数
#count(*)统计的是记录数
mysql> select count(*) from employee;
+----------+
| count(*) |
+----------+
|        5 |
+----------+
1 row in setmysql>
#统计员工表的员工所在部门数
#统计的是非NULL值
mysql> select count(dept_id) from employee;
+----------------+
| count(dept_id) |
+----------------+
|              4 |
+----------------+
1 row in set
#统计的是非 NULL 值,并且去重
mysql> select count( distinct dept_id) from employee;
+--------------------------+
| count( distinct dept_id) |
+--------------------------+
|                        2 |
+--------------------------+
1 row in set#MIN(【DISTINCT】 expr)返回 expr 的最小值
#查询最低基本工资值
mysql> select min(basic_salary) from salary;
+-------------------+
| min(basic_salary) |
+-------------------+
| 5800              |
+-------------------+
1 row in set#MAX(【DISTINCT】 expr)返回 expr 的最大值
#查询最高基本工资值
mysql> select max(basic_salary) from salary;
+-------------------+
| max(basic_salary) |
+-------------------+
| 12000             |
+-------------------+
1 row in set#查询最高基本工资与最低基本工资的差值
mysql> select max(basic_salary)-min(basic_salary) from salary;
+-------------------------------------+
| max(basic_salary)-min(basic_salary) |
+-------------------------------------+
| 6200                                |
+-------------------------------------+
1 row in set#SUM(【DISTINCT】 expr)返回 expr 的总和
#查询基本工资总和
mysql> select sum(basic_salary) from salary;
+-------------------+
| sum(basic_salary) |
+-------------------+
| 37800.00          |
+-------------------+
1 row in set

group by + 聚合函数

#group by + 聚合函数
#统计每个部门的人数
mysql> select dept_id, count(*) from employee group by dept_id;
+---------+----------+
| dept_id | count(*) |
+---------+----------+
|       1 |        2 |
|       2 |        2 |
+---------+----------+
2 rows in set#统计每个部门的平均基本工资
mysql> select emp.dept_id,avg(s.basic_salary) from employee emp,salary s where emp.eid=s.eid group by emp.dept_id;
+---------+---------------------+
| dept_id | avg(s.basic_salary) |
+---------+---------------------+
|       1 | 8900.000000         |
|       2 | 10000.000000        |
+---------+---------------------+
2 rows in set
#统计每个部门基本工资最高者
mysql> select emp.dept_id, max(s.basic_salary) from employee emp,salary s where emp.eid=s.eid group by emp.dept_id;
+---------+---------------------+
| dept_id | max(s.basic_salary) |
+---------+---------------------+
|       1 | 12000               |
|       2 | 11000               |
+---------+---------------------+
2 rows in set
#统计每个部门基本工资之和
mysql> select emp.dept_id, sum(s.basic_salary) from employee emp,salary s where emp.eid=s.eid group by emp.dept_id;
+---------+---------------------+
| dept_id | sum(s.basic_salary) |
+---------+---------------------+
|       1 | 17800.00            |
|       2 | 20000.00            |
+---------+---------------------+
2 rows in set

注意事项

1、用count(*)、count(1),那个好呢?

  • 对于myisam引擎的表来说,没有区别,因为myisam引擎内部有一个计数器在维护着行数
  • Innodb的表,用count(*) 直接读行数,效率很低,因为Innodb真的要去数一遍所有的数据。

2、关于MySQL的group by的特殊说明

在SELECT列表中所有未包含在组函数中的列都应该是包含在group by 子句中的,也就是说,SELECT列表中最好不要出现group by子句中没有的列。

4、having筛选

having与where类似,可以筛选数据

having与where的不同点

  • where针对表中的列发挥作用,查询数据;having针对查询结果中的列发挥作用,筛选数据
  • where后面不能写分组函数;having后面可以使用分组函数
  • having只用于group by 分组统计语句
# 按照部门统计员工人数,仅显示部门人数少于3人的
mysql> SELECT dept_id,COUNT(*) AS c
FROM employee
WHERE dept_id IS NOT NULL
GROUP BY dept_id
HAVING c <3;
+---------+---+
| dept_id | c |
+---------+---+
|       2 | 2 |
+---------+---+
1 row in set#查询每个部门的平均工资,并且仅显示平均工资高于8000
mysql> select emp.dept_id,avg(s.basic_salary) as avg_salary-> from employee emp,salary s -> where emp.eid=s.eid and dept_id is not null-> group by emp.dept_id-> having avg_salary>8000;
+---------+--------------+
| dept_id | avg_salary   |
+---------+--------------+
|       1 | 8900.000000  |
|       2 | 10000.000000 |
+---------+--------------+
2 rows in setmysql>

5、order by 排序

(1)按一个或多个字段对查询结果进行排序

用法:order by col1,col2,col3,……

说明:先按col1排序,如果col1相同就按照col2排序,以此类推

​ col1,col2,col3可以是select后面的字段也可以不是

(2)默认是升序,也可以在字段后面加asc显示说明是升序,desc为降序

​ 如果两个字段排序不一样,例如

​ order by 字段1 asc, 字段2 desc

(3)order by 后面除了跟1个或多个字段,还可以写表达式、函数、别名等

#排序
# 查询员工基本工资,按照基本工资升序排序,如果工资相同,按照eid升序排序
mysql> select employee.eid,basic_salary from employee inner join salary on employee.eid=salary.eid order by basic_salary,eid;
+-----+--------------+
| eid | basic_salary |
+-----+--------------+
|   4 | 5800         |
|   2 | 9000         |
|   3 | 11000        |
|   1 | 12000        |
+-----+--------------+
4 rows in set
#查询员工基本工资,按照基本工资降序排序,如果工资相同,按照eid排列
mysql> select employee.eid,basic_salary from employee inner join salary on employee.eid=salary.eid order by basic_salary desc,eid asc;
+-----+--------------+
| eid | basic_salary |
+-----+--------------+
|   1 | 12000        |
|   3 | 11000        |
|   2 | 9000         |
|   4 | 5800         |
+-----+--------------+
4 rows in setmysql>
#统计每个部门的平均基本工资,并按照平均工资降序排列
mysql> select emp.dept_id,avg(s.basic_salary) from employee emp,salary s where emp.eid=s.eid group by emp.dept_id order by avg(s.basic_salary) desc;
+---------+---------------------+
| dept_id | avg(s.basic_salary) |
+---------+---------------------+
|       2 | 10000.000000        |
|       1 | 8900.000000         |
+---------+---------------------+
2 rows in setmysql>

6、limit 分页

limit m,n

  • m表示从下标为m的记录开始查询,第一条记录下标为0
  • n表示取出n条出来,如果从m开始不够n条记录,就有几条取几条
  • m = (page-1)*n,其中,page是页码,n表示每页显示的条目

如果第一页:limit 0,n

如果第二页:limit n,n

依次类推,得出公式 limit (page-1)*n,n

#分页
#查询员工信息,每页显示 3 条,第二页
mysql> select * from employee limit 3,3;
+-----+-------+--------+--------------------+-------+---------+
| eid | ename | gender | card_id            | ‘mid‘ | dept_id |
+-----+-------+--------+--------------------+-------+---------+
|   4 | 王五  | 男     | 123456789012115678 |     1 |       1 |
|   5 | 谷雨  | 男     | 123456789012115978 |     1 |       1 |
+-----+-------+--------+--------------------+-------+---------+
2 rows in set
#统计每个部门的平均基本工资,并显示前三名
mysql> select emp.dept_id,avg(s.basic_salary) from employee emp,salary s where emp.eid=s.eid group by emp.dept_id order by avg(s.basic_salary) desc limit 0,3;
+---------+---------------------+
| dept_id | avg(s.basic_salary) |
+---------+---------------------+
|       2 | 10000.000000        |
|       1 | 8900.000000         |
+---------+---------------------+
2 rows in setmysql>

MySQL基础篇:SELECT几种子句相关推荐

  1. MySQL基础篇:子查询

    文章目录 概述 where型子查询 from型子查询 EXISTS型子查询 复制表子查询 概述 在某些情况下,当进行一个查询时,需要的条件或数据要用另一个select语句的结果,这个时候,就要用到** ...

  2. 最全MySQL基础篇

    文章目录 导入表的问题 第三章_最基本的SELECT语句 1. SQL语言的规则和规范 1) 基本规则 2) SQL大小写规范(建议遵守) 3) 注释 4) 命名规则 2. 基本的SELECT语句 1 ...

  3. MySQL基础篇——第11章 DML(数据操作):增删改

    MySQL基础篇--第11章 DML(数据操作):增删改 1. 插入数据(增) INSERT INTO ... 使用 INSERT INTO 语句向表中插入数据(记录) 1.1 方式1:VALUES ...

  4. MySQL——基础篇

    MySQL--基础篇 一.数据库的相关概念 数据库(database) 保存有组织的数据的容器(通常是一个文件或一组文件). 表(table) 某种特定类型数据的结构化清单. 模式(schema) 关 ...

  5. Mysql基础篇(1)—— 基础概念、DML基本语法和表连接

    前言 Mysql基础篇相关的内容是看了康师傅的视频做的笔记吧 数据库相关概念 DB: 数据库(Database) ​ 存储数据的仓库,本质是一个文件系统.它保存了一系列有组织的数据. DBMS:数据库 ...

  6. mysql 基础篇(二) 账号、权限管理

    mysql 基础篇(二) 账号.权限管理.备份与还原 建立账号密码: Grant all on test.* to "cj"@"localhost" ident ...

  7. 【MySQL基础篇】数据导出导入权限与local_infile参数

    [MySQL基础篇]数据导出导入权限与local_infile参数 问题背景 数据导出测试 创建测试库(在主库进行) 测试数据导出(在从库进行) 测试数据导入(在主库进行) 问题背景 MySQL高可用 ...

  8. 深入浅出Mysql - 基础篇(列类型/运算符/函数)

    深入浅出Mysql - 基础篇(列类型/运算符/函数) 每一个常量.变量和参数都有数据类型,它用来指定一定的存储格式.约束和有效范围.MySQL提供了多种数据类型,主要包括数值型.字符串类型.日期和时 ...

  9. 一起学JAVA之【基础篇】4种默认线程池介绍

    一起学JAVA之[基础篇]4种默认线程池介绍 默认线程池创建方式 java.util.concurrent 提供了一个创建线程池的工具类Executors,里面有四种常用的线程池创建方法 public ...

  10. MySQL基础篇(一)-- SQL基础

    数据库(Database)是按照数据结构来组织.存储和管理数据的仓库,它的产生距今已有六十多年.随着信息技术和市场的发展,数据库变得无处不在:它在电子商务.银行系统等众多领域都被广泛使用,且成为其系统 ...

最新文章

  1. Microbiome:山大杜宗军团队揭示捕食性细菌新类群-慢生单胞菌目细菌独特的生境适应性...
  2. 实心和空心哪个抗弯能力强_空心砖4大优缺点一次看 便宜耐用营造大自然原始风...
  3. vue 删除页面缓存_vue项目强制清除页面缓存的例子
  4. 第十五周程序阅读-范型程序设计(5)
  5. Linux/Ubuntu下安装QQ2012
  6. 网络推广外包——企业委托网络推广外包公司提高网站流量和访问量
  7. c语言命令行选项处理函数getopt和getopt_long() 函数使用
  8. 启动namenode报错:Journal Storage Directory /var/bigdata/hadoop/full/dfs/jn/dmgeo not formatted
  9. MySQL + springboot修改时区的方法小结
  10. zabbix的安装配置
  11. jquery-滑动的选项卡
  12. GCF(1)---How to modify PICS according to FGI bits UE reported
  13. 三相桥式全控整流电路simulink仿真_维修电工实训仿真软件-电工入门与提高
  14. 用于高性能分组处理的电力线滤波
  15. 怎么记住计算机快捷键,快速记忆电脑快捷键的方法
  16. python数据建模工具_Python数据分析、挖掘常用工具
  17. Floating point exception (core dumped)解决
  18. html中a标签的种类
  19. IDEA插件translation翻译插件“翻译失败:未知错误”
  20. 全部第三方工具简介 和网址 下载

热门文章

  1. Python爬虫,利用scrapy来编写一个爬虫
  2. [python教程入门学习]Python是什么?
  3. 一个Python小白5个小时爬虫经历
  4. c++ lambda函数_C++ Lambda表达式
  5. mongodb 安装_1、MongoDB 安装
  6. 哪些因素影响数据存储系统的IOPS性能?
  7. div如何添加滚动条?
  8. c语言 8155 数码管,基于8155的8LED显示串口通信机设计 编程
  9. 读一个文件的java程序_java 读文件的几种方法(一)
  10. 【算法笔记】一步一步推出来的同余最短路优化思路(千字长文,超详细)