MySQL基础关键_003_DQL(二)
目 录
一、排序
1.语法格式
2.单一字段排序
(1)按照薪资升序查询员工编号、姓名、薪资
(2)按照入职日期降序查询员工信息
3.多个字段排序
(1)按照薪资升序,薪资相同按照姓名升序查询员工信息
4.where 与 order by 的顺序
(1)按照薪资升序,查询职位是“CLERK”的员工信息
(2)执行顺序
二、去重
1.查询所有职位
2.语法规则
3.查询所有部门编号所有职位
三、数据处理函数1
1.字符串相关
(1)利用 upper 或 ucase 转大写
(2)利用 lower 或 lcase 转小写
(3)利用 substr 截取字符串
(4)利用 length 获取字符串长度
(5)利用 char_length 获取字符个数
(6)利用 concat 拼接字符串
(7)利用 trim 去除字符串前后内容
2.数字相关
(1)利用 rand 生成 0~1 的随机浮点数
(2)利用 round 四舍五入
(3)利用 truncate 舍去小数
(4)利用 ceil 和 floor 返回整数
一、排序
1.语法格式
- 【select… from… order by 字段 asc/desc;】;
- asc:升序;
- desc:降序;
- 默认按照升序排序;
- 其中,字段名可以用列编号代替,例如:1,2,3……。但是不推荐使用。
2.单一字段排序
(1)按照薪资升序查询员工编号、姓名、薪资
select emp_no, emp_name, salary from employees order by salary asc;
(2)按照入职日期降序查询员工信息
select * from employees order by hire_date desc;
3.多个字段排序
(1)按照薪资升序,薪资相同按照姓名升序查询员工信息
select * from employees order by salary asc, emp_name asc;
4.where 与 order by 的顺序
(1)按照薪资升序,查询职位是“CLERK”的员工信息
select * from employees where job_title = 'CLERK' order by salary asc;
(2)执行顺序
- 首先,执行 from 语句;
- 其次,执行 where 语句;
- 再次,执行 select 语句;
- 最后,执行 order by 语句。
二、去重
1.查询所有职位
select distinct job_title from employees;
2.语法规则
- distinct 只能出现在所有字段最前方;
- 存在 distinct 后,之后的字段是联合去重的。
3.查询所有部门编号所有职位
select distinct dept_no, job_title from employees;
三、数据处理函数1
1.字符串相关
(1)利用 upper 或 ucase 转大写
查询员工姓名,大写输出。
# upper
select upper(emp_name) from employees;# ucase
select ucase(emp_name) from employees;
(2)利用 lower 或 lcase 转小写
查询员工姓名,小写输出。
# lower
select lower(emp_name) from employees;# lcase
select lcase(emp_name) from employees;
(3)利用 substr 截取字符串
查询员工姓名中第二个字母是 A 的员工。
select emp_name from employees where substr(emp_name, 2, 1) = 'A';
(4)利用 length 获取字符串长度
一个汉字是两个长度。
select length('你好啊,5201314');
(5)利用 char_length 获取字符个数
只是获取字符个数,区别上方 length。
select char_length('你好啊,5201314');
(6)利用 concat 拼接字符串
- 语法:【concat('字符串1', '字符串2', '字符串3',……);】;
- 在 MySQL 8 之前,还可以借助【 || 】实现字符串拼接。但 MySQL 8 之后,其只作为逻辑运算符。
select concat('I ', 'Love ', 'You!');
(7)利用 trim 去除字符串前后内容
- 可以去除前后空白;
- 也可以去除指定前缀、后缀。
# 去除前后空白
select concat('I', trim(' miss '), 'you.');# 去除前缀
select trim(leading 'I' from 'IIIIII hate you!!!');# 去除后缀
select trim(trailing '!' from 'IIIIII hate you!!!'); # 去除前后缀
select trim(both 'H' from 'HHHHHHateHHHHHH');
2.数字相关
(1)利用 rand 生成 0~1 的随机浮点数
若想要一直获得同一个随机数,只需在 rand() 的括号内指定一个整数。
# 1
select rand();# 2
select rand();# 3
select rand(99);# 4
select rand(99);
(2)利用 round 四舍五入
- round(x):四舍五入,只保留整数位;
- round(x, y):四舍五入,保留 y 位小数。
# round(x)
select round(3.15);# round(x, y)
#select round(3.15, 1);
(3)利用 truncate 舍去小数
truncate(x, y):对 x 保留 y 位小数,其余全部舍去。
select truncate(3.1415926, 3);
(4)利用 ceil 和 floor 返回整数
ceil(x):返回大于或等于数值 x 的最小整数;
floor(x):返回小于或等于数值 x 的最大整数。
# ceil(x)
select ceil(3.14);# floor(x)
select floor(3.14);