SQL基础——函数与约束

声明:以下内容为根据黑马数据库视频教程,个人整理的笔记,方便记录学习。

知识导图

在这里插入图片描述

案例SQL语句编写

一、函数

1.字符串函数

A. concat : 字符串拼接

SELECT CONCAT('hello',' world!');
# 输出:hello world!

B. lower : 全部转小写

select LOWER('Hello');
# 输出:hello

C. upper : 全部转大写

select UPPER('Hello');
# 输出:HELLO

D. lpad : 左填充

select LPAD('你好',5,'000');
# 输出:000你好

E. rpad : 右填充

select RPAD('你好',5,'000');
# 输出:你好000

F. trim : 去除空格

select TRIM(' hello world! ');
# 输出:hello world!

G. substring : 截取子字符串

select SUBSTRING('hello world!',3,2);
# 输出:ll

2.数值函数

A. ceil:向上取整

select ceil(1.1);
#输出2

B. floor:向下取整

select floor(1.9);
#输出1

C. mod:取模

select mod(7,4);
#输出3

D. rand:获取随机数

select rand();
# 输出0.5759448675214731
#获取随机数0~1以内

E. round:四舍五入

select round(2.1234,2);
#输出2.12(给2.1234保留两位小数,并四舍五入)

综合案例
通过数据库的函数,生成一个六位数的随机验证码

select lpad(ceil(rand()*1000000),6,'0')

说明:加上lpad()是为了防止rand()函数生成的随机数是0.03…这种,再乘以1000000,结果就会变为五位。

3.日期函数

A. curdate:当前日期

select curdate();
# 输出2024-07-11

B. curtime:当前时间

select curtime();
# 输出14:40:09

C. now:当前日期和时间

select now();
# 输出2024-07-11 14:40:50

D. YEAR , MONTH , DAY:当前年、月、日

select year(now());# 输出2024
select month(now());# 输出7
select day(now());# 输出11

E. date_add:增加指定的时间间隔

select date_add('2024-07-11',interval 10 day);
# 输出 2024-07-21

select day(date_add(now(),interval 10 day));
# 今天是2024年7月11日,则这条语句输出21

F. datediff:获取两个日期相差的天数 (注意:前-后)

select datediff('2024-07-11','2024-07-05');
# 输出 6

综合案例
查询所有员工的入职天数,并根据入职天数倒序排序

select name, datediff(curdate(), entrydate) as 'entrydays' from emp order by entrydays desc;

4.流程函数

A. if

select if(true,1,0);
# 输出1

B. ifnull

select ifnull('hhh','ggg');
# 输出hhh

select ifnull('','ggg');
# 输出

select ifnull(false,'ggg');
# 输出0

select ifnull(null,'ggg');
# 输出ggg

C. case when then else end
查询emp表的员工姓名和年龄阶段

select employeename as '姓名', 
	(case when age<18 then '未成年'
	when age<=30 then '青年'
	else '中年'
	end) as '年龄阶段'
from emp;

原表:
在这里插入图片描述
运行SQL语句后的结果:
在这里插入图片描述

二、约束

在这里插入图片描述
根据需求,完成表结构的创建:

create table user(
    id int auto_increment primary key comment '唯一标识',
	name varchar(10) not null unique comment '姓名',
	age int comment '年龄',
	status char(1) default '1' comment '状态',
	gender char(1) comment '性别'
) comment '员工表';
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值