常用SQL函数使用
-- 新建一张表 drop table if exists T_EAGLE_INFO; create table T_EAGLE_INFO ( ID int primary key auto_increment comment 'PK', EAGLE_NAME varchar(100) not null comment '开发平台名称', EAGLE_DESC varchar(32) not null comment '开发平台描述', EAGLE_VERSION varchar(10) not null comment '开发平台版本', GMT_VREATE datetime(6) not null comment '创建日期 格式:YYYY-MM-DD hh:mm:ss UUUUUU', GMT_MODIFIED datetime(6) not null comment '修改日期 格式:YYYY-MM-DD hh:mm:ss UUUUUU' )engine=innodb default charset=utf8 comment '开发平台版本表'; -- 函数学习 -- 一、字符函数 -- 1、length 获取字符串的长度 select length('chenhan'); -- 7 select length('昊昊111'); -- 9 -- 2、concat 拼接字符串 select concat(EAGLE_NAME,'_',EAGLE_DESC) from T_EAGLE_INFO; -- 开发一组_互联网 -- 3、upper、lower select upper('HAOhao'); -- HAOHAO select lower('HAOhao'); -- haohao -- 4、sbstr|sunstring 字符串截取[索引从1开始] select substring('昊昊爱吃炸鸡翅',5); -- 炸鸡翅[5,length] select substr('昊昊爱吃炸鸡翅',1, 2); -- 昊昊[1,2] -- 5、instr 获取字符串的起始索引 select instr('昊昊爱吃炸鸡翅','昊'); -- 1(第一次出现的位置,如果找不到返回0) -- 6、trim 去空格[只能去前后的空格] select trim(' 昊昊 爱吃炸 鸡翅 '); -- 7、lpad 使用指定字符左填充 -- rpad 使用指定字符右填充 select lpad('昊昊',5,'*'); -- ***昊昊 select rpad('昊昊',5,'*'); -- 昊昊*** -- 8、replace 替换指定字符串 select replace('昊昊爱吃炸鸡翅','昊昊','涵涵'); -- 涵涵爱吃炸鸡翅 -- 二、数学函数 -- 1、round 四舍五入 select round(-4.6); -- -5 -- 2、ceil 向上取整 -- floor 向下取整 select ceil(-2.3); -- -2 select floor(-2.3); -- -3 -- 3、truncate 截取 select truncate(1.599999,3); -- 1.599 -- 4、mod 取余 select mod(10,3); -- 1 select mod(10,-3); -- 1 select mod(-10,3); -- -1 select mod(-10,-3); -- -1 -- 三、日期函数 -- 1、now 返回当前系统的日期和时间 select now(); -- 2020-08-06 15:45:59 -- 2、curdate 返回当前系统日期,不包含时间 select curdate(); -- 2020-08-06 -- 3、curtime 返回当前系统时间,不包含日期 select curtime(); -- 15:47:56 -- 4、获取指定的部分,年year、月month、日day、时hour、分minute、秒second select year(now()); -- 2020 select month(now()); -- 8 select day(now()); -- 6 select hour(now()); -- 15 select minute(now()); -- 52 select second(now()); -- 33 -- 5、datediff 计算时间差 select datediff('2020-12-8', now()); -- 124 select datediff('2020-12-8', '2020/12/1'); -- 7 -- 5、str_to_date 字符转指定日期 select str_to_date('2020-8-6','%Y-%m-%d'); -- 2020-08-06 -- 6、date_format 将日期转换为字符 select date_format(now(),'%Y年%m月%d日'); -- 2020年08月06日 -- 四、流程控制函数 -- 1、if select if(10>20,'true','false'); -- false -- 2、case函数 /* 语法1、 case 要判断的字段或表达式 when 常量1 then 要显示的值或者语句1; when 常量2 then 要显示的值或者语句2; …… else 要显示的值n或语句n; end */ /* 案例: 学生奖励: 第一名奖励500元; 第二名奖励300元; 第三名奖励100元; 其他不奖励; */ select score 学生成绩,id 学生排名, case id when 1 then 500 when 2 then 300 when 3 then 100 else 0 end as 奖励 from student; /* 语法2: case when 条件1 then 要显示的值或者语句1; when 条件2 then 要显示的值或者语句2; …… else 要显示的值n或语句n; end */ /* 案例: 学生成绩: 90分以上奖励500元; 80-90分奖励300元; 70-80分奖励100元; 其他不奖励; */ select score 学生成绩, case when score between 90 and 100 then 500 when score between 80 and 90 then 300 when score between 70 and 80 then 100 else 0 end as 奖励 from student; -- 五、分组函数 -- 1、求和sum、平均值avg、最大值max、最小值min、计算个数count -- 2、group by 分组函数【分组前筛选where,分组后筛选having】