一、函数
指一段可以直接被另一端程序调用的程序和代码
1.字符串函数

sql
-- 1.字符串拼接
select concat('hello',',','mysql');
-- 2.将字符串全部转为小写
select lower('Hello MySQL');
-- 3.转为大写
select upper('hello,MySQL');
-- 4.左填充 将字符串pad 对str 的左边进行填充直到达到n的字符串长度
-- select lpad(str,n,pad)
select lpad('1',5,'-');
-- 5.右填充
select rpad('1',5,'-');
-- 6.去除字符串头部和尾部的空格
select trim(' Hello MySQL ');
-- 7.返回从字符串str 从start 位置起的len个长度的字符串
-- substring(str,start,len)
-- 第一个字符为索引1
select substring('Hello MySQL',1,6)
2.数值函数

sql
-- 二、数值函数
-- 1.cell(x) 向上取整
select ceil(122.5);
-- 2.floor 向下取整
select floor(122.5);
-- 3.mod(x,y) 返回x/y 的模
select mod(12,5);
-- 4.rand() 返回0~1的随机数
select rand();
-- 5.round(x,y) 求参数x的四舍五入的值 保留y 位小数
select round(12.225,2);
-- 练习 求随机六位数验证码
select lpad((round(rand(),6)*1000000),6,0);
3.日期函数

sql
-- 三、日期函数
-- 1.curdate() 返回当前日期
select curdate();
-- 2.curtime() 返回当前时间
select curtime();
-- 3.now() 返回 当前日期 + 时间
select now();
-- 4.year(date) 获取指定date 年份
select year('2025-1-15');
-- 5.mouth(date)
-- 6.day(date)
-- 7.date_add(date,interval expr type) 返回一个日期/时间值加上一个时间间隔expr后的时间值
select date_add('2025-1-15',interval 70 day); -- 2025-1-15往后退七十天
-- 8.datediff(date1,date2) 返回起始时间与结束时间date2之间的天数 (date1 - date2)
select datediff(now(),'2025-1-15');
select datediff(now(),'2006-10-14');
4.流程函数

sql
-- 三、流程函数
-- 1.if(value,t,f) 如果value为true 则返回t,否则返回f
select if(2,'ok','error');
-- 2.ifnull(value1,value2) 如果value1不为空则返回value1 否则返回value2
select ifnull('ok','error');
-- 3.case when [val1] then [res1] ... else [default] end
-- 如果val1为true 则返回res1, ... 否则返回default默认值
select
id,
name,
(case employee.workno when 1 then 'No1' when 2 then 'No2' else 'hide' end) as '序号',
case when math >= 85 then '优秀' when math >=60 then '及格' else '不及格' end
from employee;
-- 4.case [expr] when [val1] then [res1] ... else [default] end
-- 如果 expr 的值等于val1 ,则返回res1,...否则返回default默认值
二、约束
作用于表中字段上的规则,用于限制存储在表中的数据
保证数据库中数据的正确、有效性、和完整性
1.分类
sql
-- 创建表
create table user (
id int primary key auto_increment comment '主键',
name varchar(10) not null unique comment '姓名',
age int check ( age > 0 && age < 120) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '性别'
) comment '用户名';
-- primary key : 主键约束(非空 且 唯一)
-- auto_increment : 自动增长
-- not null : 非空约束
-- check () : 检查约束
-- default ' ' : 默认约束 '默认值'
-- 插入数据
insert into user(name,age,status,gender) values ('Tom1','19','1','男'),('Tom2','21','1','女')
-- 注意 插入name 时候如果失败也会自动增长id?
2.学会用DataGrip 自动生成约束
3.外键约束

sql
-- 添加外键
alter table emp add constraint fl_emp_dept_id foregin key (dept_id) references dept(id);
--删除外键
alter table emp drop foregin key fk_emp_dept_id;


