Mysql数据库(九)——mysql高阶语句(下)
一、函数
1、数学函数
数学函数 | 描述 |
---|
abs(x) | 返回 x 的绝对值 |
rand() | 返回 0 到 1 的随机数 |
mod(x,y) | 返回 x 除以 y 以后的余数 |
power(x,y) | 返回 x 的 y 次方 |
round(x) | 返回离 x 最近的整数 |
round(x,y) | 保留 x 的 y 位小数四舍五入后的值 |
sqrt(x) | 返回 x 的平方根 |
truncate(x,y) | 返回数字 x 截断为 y 位小数的值 |
ceil(x) | 返回大于或等于 x 的最小整数 |
floor(x) | 返回小于或等于 x 的最大整数 |
greatest(x1,x2…) | 返回集合中最大的值 |
least(x1,x2…) | 返回集合中最小的值 |
select abs(-1),rand(),mod(5,3),power(2,3),round(5.5),round(5.785,2),round(5.784,2),sqrt(4);

select truncate(3.755,2),ceil(5.2),floor(5.2),greatest(1,2,3),greatest(1,2,'a'),least('a','b','c'),least(1,2,null);

2、聚合函数
聚合函数 | 描述 |
---|
avg() | 返回指定列的平均值 |
count() | 返回指定列中非 NULL 值的个数 |
min() | 返回指定列的最小值 |
max() | 返回指定列的最大值 |
sum(x) | 返回指定列的所有值之和 |
select avg(id) from ljm;
select count(id) from ljm;
select min(id) from ljm;
select max(id) from ljm;
select sum(id) from ljm;

3、字符串函数
字符串函数 | 描述 |
---|
trim() | 返回去除指定格式的值 |
concat(x,y) | 将提供的参数 x 和 y 拼接成一个字符串 |
substr(x,y) | 获取从字符串 x 中的第 y 个位置开始的字符串,跟substring()函数作用相同 |
substr(x,y,z) | 获取从字符串 x 中的第 y 个位置开始长度为 z 的字符串 |
length(x) | 返回字符串 x 的长度 |
replace(x,y,z) | 将字符串 z 替代字符串 x 中的字符串 y |
upper(x) | 将字符串 x 的所有字母变成大写字母 |
lower(x) | 将字符串 x 的所有字母变成小写字母 |
left(x,y) | 返回字符串 x 的前 y 个字符 |
right(x,y) | 返回字符串 x 的后 y 个字符 |
repeat(x,y) | 将字符串 x 重复 y 次 |
space(x) | 返回 x 个空格 |
strcmp(x,y) | 比较 x 和 y,返回的值可以为-1,0,1 |
reverse(x) | 将字符串 x 反转 |
select trim(' 123abc');
select concat('abc',123);
select substr('abcdefg',3);
select substr('abcdefg',3,2);
select length('abcdefg');
select replace('abcdefg','a','1');
select upper('abc');
select lower('ABC');
select left('abcdefg',3);
select right('abcdefg',3);
select repeat('abc',2);
select length(space(3));
select strcmp(1,2),strcmp(2,2),strcmp(3,2);
select reverse('abcdefg');

4、日期时间函数
日期时间函数 | 描述 |
---|
curdate() | 返回当前时间的年月日 |
curtime() | 返回当前市价你的时分秒 |
now() | 返回当前时间的日期和时间 |
month(x) | 返回日期x中的月份值 |
week(x) | 返回日期x是年度的第几个周 |
hour(x) | 返回x中的小时值 |
minute(x) | 返回日期x中的分钟值 |
second(x) | 返回日期x中的秒数值 |
dayotweek(x) | 返回x是星期几,1为星期日,2为星期一 |
replace(x,y,z) | 将字符z替代字符串x中的字符串y |
dayotmonth(x) | 计算日期x是本月的第几天 |
dayotyear(x) | 计算日期x是本年的第几天 |
select dayofweek(curtime());
select dayofmonth(curtime());
select dayofyear(curtime());
select curdate();
select curtime();
select now();

二、存储过程
1、简介
2、优点
3、语法
create procedure <过程名> ([过程参数……]) <过程体>
[过程参数……] 格式
<过程名>:尽量避免与内置的函数或字段重名
<过程体>:语句
[in|out|inout] <参数名><类型>
①、例
例:
delimiter $$ #将语句的结束符号从分号;临时修改,以防出问题,可以自定义
create procedure ee(in inname varchar(16)) #创建存储过程,过程名自定义,()可带参数
begin #过程体以关键字BEGIN开始
select * from test1 where a_name='aaaa'; #过程体语句
end$$ #过程体以关键字END结尾
delimiter ; #将语句的结束符号恢复为分号
call ee('aaaa'); #调用存储过程
--------------查看存储过程--------------
show create procedure XXX\G #查看某个储存过程的具体信息


②、参数分类
③、带参数的存储过程

④、修改存储过程
alter procedure <过程名> [<特征>……]
alter procedure ff modifies sql data sql security invoker;
modifies sql data:表名子程序包含写程序的语句
security:安全等级
invoker:当定义为 invoker 时,只要执行者有执行权,就可以成功执行
⑤、删除存储过程
drop procedure if exists ff;
