首页 > 数据库 >MySQL 函数 function

MySQL 函数 function

时间:2022-10-21 21:00:47浏览次数:44  
标签:function group 函数 -- curdate MySQL hello select name

函数

  • 内置函数function

    • 字符串

      -- 常用函数串操作函数
      set @str = 'hello中国';
      select @str,length(@str),char_length(@str),character_length(@str),reverse(@str);
      select space(6),repeat('*',10),left(@str,2),mid(@str,2,3),right(@str,3);
      
      select rand(),round(1.5),round(1.2),floor(1.1),floor(1.9),ceil(1.1),ceil(1.9);
      select repeat('*',round(rand()*9+1));
      
      select 5%3,mod(5,3);
      -- 字符串连接
      select concat('hello','mysql','java'),concat_ws('--','hello','mysql','java');
      
      -- 会计,法学,美术,计算机科学,计算机网络
      select group_concat(distinct dept) from stu;
      
      -- 会计-法学-美术-计算机科学-计算机网络
      select group_concat(distinct dept separator '-') from stu;
      
      select name,group_concat(id order by id desc separator '_') from t group by name;
      -- jack 7
      -- andy 6_5_1
      -- mary 4_2
      
      select name,group_concat(id) from stu group by name;
      select name,group_concat(id order by id desc) from stu group by name;
      select name,group_concat(id order by id desc separator '_') from stu group by name;
      
      
      -- 字符串替换 hello-mysql
      select replace('hello-java','java','mysql')
      
      -- 检查字符串的位置 7
      select position('java' in 'hello-java');
      -- 3
      select instr('hello','llo');
      -- 0
      select instr('hello','allo');
      
      -- uuid随机字符串,加密
      select uuid(),md5('1'),sha('1'),sha1('a')
      
      select lower('HELLO'),upper('hello');
      
      -- 相当于字符串插入 helljavao
      select insert('hello',5,0,'java');
      -- helljava
      select insert('hello',5,1,'java') ;
      -- 转换base64字符串 aGVsbG/kuK3lm70=   hello中国
      select to_base64(@str),from_base64('aGVsbG/kuK3lm70=');
      
      
      
      select substr('hello' from 3),substring('hello' from 3);
      select substring('hello',3);
      select substring('hello' from 3);
      select substring('hello',3,1);
      select substring('hello123456',3),substring('hello123456',-3)
      
      -- substring_index() 
      select substring_index('www.mysql.com.cn','.',1);
      select substring_index('www.mysql.com.cn','.',-1);
      select substring_index('www.mysql.com.cn','.',-2);
      
      -- ip 转换函数
      select inet_ntoa(978559132),inet_aton('58.83.160.156')
      select inet_aton('58.83.160.156');
      
      
    • 日期、时间、时间戳相关函数

      -- 日期相关函数
      -- 日期     时间
      select curdate(),current_date(),curtime(),current_time();
      -- 日期时间
      select now(),sysdate(),current_timestamp();
      -- 时间戳
      select unix_timestamp(),from_unixtime(0),from_unixtime(1622018477)
      
      -- 日期时间格式化
      select date_format(curdate(),'%Y-%m-%d %H:%i:%s');
      select date_format(now(),'%Y-%m-%d %H:%i:%s');
      select from_unixtime(unix_timestamp(),'%Y年%m月%d日%H时%i分%s秒');
      select date_format(curdate(),'%m月%d日');
      
      select year('2018-2-16'),month(curdate()),day(curdate()),date(now()),time(now());
      select hour(curtime()),minute(curtime()),second(curtime());
      
      -- 日期计算
      -- 本月第一天日期 最后一天日期 三天前的日期 5天后日期
      select now(),date_add(now(),interval -3 day),date_add(now(),interval 5 day),date_add(now(),interval -100 hour );
      
      
      -- 计算两个日期有多少天 now() - 2000-1-16
      select to_days(curdate()) - to_days('2000-1-16');
      
      -- 求指定日期的那个月最后一天日期 ,返回日期,没有时分秒
      select last_day(curdate()),last_day('2000-2-4'),last_day(now());
      select day(curdate()),dayname(curdate()),dayofmonth(curdate()),dayofweek(curdate()),dayofyear(curdate());
      select concat_ws('-',year(curdate()),month(curdate()),1);
      -- 获取当月第一天日期
      select date_add(curdate(),interval -day(curdate())+1 day);
      
      -- 获取当前月的总天数
      select day(last_day('2021-2-3'));
      
      select date_add(curdate()-day(curdate())+1,interval -1 month); -- 获取下个月的第一天
      
      -- date_diff
      select datediff(curdate(),'2018-3-15');
      select timestampdiff(day,'2018-3-15',curdate())
      select timestampdiff(year,'2018-3-15',curdate())
      select timestampdiff(hour,'2021-5-25 08:30:50','2021-5-25 18:20:30')
      
      
    • select user(),database(),version(),now();
      
      select * from stu;
      
      -- 查看stu中有多少个专业
      select count(distinct dept) from stu;
      
      select distinct dept from stu;
      
      -- 每个专业的人数
      select dept,count(*) from stu group by dept;
      
      
      select distinct dept from stu order by dept desc;
      select group_concat(distinct dept order by dept desc) from stu;
      set @ss = '计算机网络,计算机科学,美术,法学,会计';
      
      -- 计算机科学,美术,法学
      select substring_index(substring_index(@ss,',',4),',',-3)
      
      select reverse(substring_index(reverse(substring_index(@ss,',',4)),',',3));
      --
      
      select substring_index(group_concat(distinct dept order by dept desc),',',1) from stu;
      
      SELECT SUBSTRING_INDEX(CURRENT_USER(),'@',1);
      
      
      select name,group_concat(id) from (
      select id,name from stu  limit 10) ttt group by name;
      
      id name pid
      1 电器   2,3
      
      select group_concat(distinct name order by name desc) from stu;
      
      -- if()  ifnull()
      select if(true,'yes','no'),ifnull(null,'hello'),ifnull('a','b');
      
      select id,name,ifnull(gender,'保密'),if(gender is null,'保密',gender) from stu;
      
  • 自定义函数

-- 自定义函数
delimiter $
create function pf(i int)
    returns int
begin
    return i * i;
end$
delimiter ;

-- 查看声明了哪些函数
show function status where Db = 'wxdb';

select `SPECIFIC_NAME`
from `INFORMATION_SCHEMA`.`ROUTINES`
where `ROUTINE_SCHEMA` = 'wxdb'
  and ROUTINE_TYPE = 'FUNCTION';

-- 调用函数
select pf(19), pf(2), pf(6);

-- 声明函数 返回等级 >90优秀 >80良好 >60 及格 else 补考
delimiter $$
create function f_level(s int)
    returns varchar(2)
begin
    return if(s >= 90, '优秀', if(s > 80, '良好', if(s >= 60, '及格', '补考')));
end $$
delimiter ;
-- 删除定义的函数
drop function `f_level`;

-- 调用函数
select f_level(90);

-- 在一个表的查询中使用函数
select f_level(score) le, count(*), group_concat(concat_ws('-', id, name))
from stu
group by le;

-- 自定义函数实现 留言动态计算效果
/*
 1 jack helloworld 2021-05-27 10:42:15

 1 jack hellowrld


 */
select uuid(), length(uuid())
create table cf_guestbook
(
    id      char(36)     not null,
    name    varchar(30)  not null,
    msg     varchar(255) not null,
    addtime datetime default now(),
    primary key (id)
);

select *
from cf_guestbook;
insert cf_guestbook
values (uuid(), 'jack', 'helloworld', '2021-5-3 18:20:30'),
       (uuid(), 'lisi', '你好呀', '2021-5-27 8:3:50'),
       (uuid(), 'lisi', '在干什么?', now());

-- 声明定义函数
delimiter $
create function f_addtime(t datetime)
    returns varchar(100)
begin
    declare t1 int;
    declare t2 int;
    declare m varchar(30);
    set t1 = unix_timestamp();
    set t2 = unix_timestamp(t);
    if t1 - t2 < 60 then
        set m = '刚刚';
    elseif t1 - t2 < 3600 then
        set m = concat(round((t1 - t2) / 60), '分钟前');
    elseif t1-t2 < (3600*24)  then
        set m = concat(round((t1 - t2) / 3600), '小时前');
    else
        set m = from_unixtime(t2);
    end if;

    return m;
end $
delimiter ;

drop function f_addtime;
select name, msg, f_addtime(addtime)
from cf_guestbook;
-- select unix_timestamp(),unix_timestamp(addtime) from cf_guestbook;

image-20210527115408386

标签:function,group,函数,--,curdate,MySQL,hello,select,name
From: https://blog.51cto.com/lianghecai/5784580

相关文章

  • MySQL 存储过程 procedure
    存储过程procedureMySQL5.0版本开始支持存储过程。存储过程(StoredProcedure)是一种在数据库中存储复杂程序,以便外部程序调用的一种数据库对象。存储过程是为了完成特......
  • 函数的单调性
    函数的单调性\[定理1.设函数f(x)在[a,b]上连续,在(a,b)上可导\\(1)如果在(a,b)内f'(x)\geq0,且等号仅在有限多个点处成立,则函数f(x)在[a,b]上单调增加\\(2)如果再(a,b)......
  • 09-JS函数入门总结
    JS函数简单入门知识点总结1.1函数的概念函数:为完成一个操作任务而组合在一起的的语句组,实现了程序的三大逻辑(顺序、分支和循环)1.2函数的作用减少重复的代码,方便......
  • Mysql 5.7 忘记root密码或重置密码的详细方法
    1、修改配置文件my.cnf按i编辑[root@mihutao~]#vim/etc/my.cnf在[mysqld]中添加skip-``grant``-tables例如:[mysqld]``**skip-``grant``-tables**``datadir=/var......
  • JUnit测试单元进行函数测试时不能使用Scanner的解决方案
    方案一:1.在idea的安装目录里面的bin目录下找到 idea64.exe.vmoptions 文件2.编辑该文件,在文件末尾加上如下指令-Deditable.java.test.console=true 3.重启i......
  • mysql--索引
    来源:https://zhuanlan.zhihu.com/p/453658511 1、什么是索引索引其实是⼀种数据结构,能够帮助我们快速的检索数据库中的数据 2、索引的优点缺点优点:......
  • 华为云数据库 RDS for MySQL ,助力数字化企业安全发展​
    在云计算、大数据和人工智能高速发展的云2.0时代,传统的数据库已然难以适应海量信息数据、高计算高性能的计算级运行,不能搭配LAMP,不能适应WEB开发的要求。网络运营单位开始追......
  • 通俗易懂的MySQL事务及MVCC原理,我先收藏了!
    一、事务简介与四大特性事务指的是一组命令操作,在执行的过程中,要么全部成功,要么全部失败。由引擎层支持事务,MyISAM就不支持事务,而InnoDB是支持事务的。事务具有以下四大特性......
  • 10-JS创建项目与连接Mysql总结
    JS创建项目与连接Mysql总结一、npm介绍二、NodeJS在VScode环境下创建项目首先新建一个项目文件夹右键该文件夹,选择在终端打开菜单项在VScode提供的终端环境下......
  • 使用MySQL Proxy实现读写分离的正确操作
    环境:CentOS7本文适用于包括Docker的所有环境,Docker安装这里不在阐述。第一步从官网下载tar包。官网链接:https://downloads.mysql.com/archives/proxy/a)直接在CentOS上......