MySQL笔记--SQL函数和约束

目录

1--函数

1-1--字符串函数

1-2--数值函数

1-3--日期函数

1-4--流程函数

2--约束

2-1--外键约束


1--函数

1-1--字符串函数

常用字符串函数如下:

代码实例:

# 拼接两个字符串
select concat('hello' ' mysql');

# 转小写
select lower('HELLO');

# 转大写
select upper('hello');

# 左填充
select lpad('123', 5, '0');
# 右填充
select rpad('123', 5, '0');

# 去除首尾空格
select trim(' hello mysql ');

# 取子串
select substring('I love hello mysql', 1, 6);

1-2--数值函数

常用数值函数如下:

代码实例:

# 向上取整
select ceil(1.1);

# 向下取整
select floor(1.9);

# 取模
select mod(7, 4);

# 返回(0, 1)随机数
select rand();

# 计算四舍五入
select bound(3.144, 2); # 保留两位小数
select bound(3.145, 2);

1-3--日期函数

常用日期函数如下:

代码实例:

# 获取当前日期
select curdate();

# 获取当前时间
select curtime();

# 获取当前日期和时间
select now();

# 获取年份
select year('2023-11-07');

# 获取月份
select month('2023-11-07');

# 获取日期
select day('2023-11-07');

# 从今天开始,计算100天后的日期
select date_add(now(), interval 100 day);

# 计算两个日期相差的天数
select datediff('2023-11-07', '2024-02-15');

1-4--流程函数

常用流程函数如下:

代码实例:

select if(true, 'yes', 'no');

select ifnull(null, 'default');

select ifnull('', 'default');

2--约束

        约束是作用于表中字段上的规则,用于限制存储在表中的数据,其目的是保证数据库中数据的正确、有效性和完整性;

常见约束:

代码实例:

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 '用户表';

2-1--外键约束

        通过添加外键可以关联两个表格;

# 添加外键语法
alter table 表名 add constraint 外键名称 foreign key(外键字段名) references 主表(主表列名);

# 在 emp 表中添加外键,将 emp 表中的 dep_id 与 dept 表中的 id 进行关联
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) reference dept(id);

# 删除外键
alter table 表名 drop foreign key 外键名称;

# 删除在emp表中添加的外键 fk_emp_dept_id
alter table emp drop foreign key fk_emp_dept_id;

在添加外键时设置相应的行为,可以确保两个关联表之间数据的删除和更新;

# 基本语法
alter table 表名 add constraint 外键名称 foreign key (外键字段) references 主表名(主表字段名) on update 行为 on delete 行为;

# 同步更新的代码
alter table emp add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade;

猜你喜欢

转载自blog.csdn.net/weixin_43863869/article/details/134256063