【mysql】 1.mysql基础入门

一、mysql基础入门

  1. 常见函数

1
2
3
4
5
6
类似与java的方法,将一组逻辑语句封装在方法体中,对外暴露方法名
好处:隐藏了实现细节;提高代码的重用性
调用:select 函数名(实参列表) from 表名;
特点:叫什么(函数名);干什么(函数功能)
分类:1.单行函数:如-contact lenth ifnull等
2.多行函数:功能:做统计使用,又称为统计函数,聚合函数,组函数
  • 单行函数:字符函数、数学函数、日期函数、其他函数、流程控制函数字符函数
字符函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 1.length 获取参数值的字节个数
select length('tom') # 3
# 2.contact 拼接字符串
select contact(last_name,'-',first_name) as 姓名 from user;
# 3.upper、lower 大小写转换
select upper('Tom')
select lower('Tom')
# 4.substr、substring 截取参数值
select substr(string,position,length) output; # 索引从1开始
# 5.instr 获取参数的某字符的开始位置,如果找不到返回0
select instr("你好我是一个傻子",'傻子') #7
# 6.trim 去掉字符串的两端空格
select trim(" Tim ") as name; # 去掉两端空格
select trim('a' from 'aaaaaaaaaaaa你好aaaaa你好aaaaaaa') as output # 去掉两端的a字符
# 7.lpad 用指定的字符实现左填充,超过会从右截断
select lpad('我是',10,‘*’) as output
# 8.rpad 用指定的字符实现右填充,超过会从右截断
select rpad('我是一个傻子',10,‘*’) as output
# 9.replace 替换字符串
select replace('张无忌爱上了周芷若','周芷若','赵敏')
数学函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 1.round 四舍五入
select round(1.65) # 2
select round(1.568,2) # 小数点后保留两位 1.57
# 2.ceil 向上取整(返回大于等于参数的最小整数)
select ceil(1.00) # 1
select ceil(0.01) # 1
# 3.floor 向下取整(返回小于等于参数的最大整数)
select floor(-9.99) # -10
# 4.truncate 截断
select truncate(1.65,1) # 1.6 小数点后保留一位
# 5.mod 取余 mod(a,b) a-a/b*b
select mod(10,3) # 1
select mod(-10,-3) # -1 被除数为正则正
select mod(10,-3) # 1 被除数为负则负
日期函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 1.now 返回当前系统日期+时间
select now();
# 2.curdate 返回当前系统日期,不包含时间
select curdate();
# 3.curtime 返回当前时间,不包含日期
select curtime();
# 4.可以获取指定的部分,年,月,日,时,分,秒等等
select year(now()) 年;
select year('1998-01-01') 年;
select month('1998-01-01') 月;
select monthname('1998-01-01') 月; # 出现月份的英文
# str_to_date:将日期格式的字符转换成指定格式的日期
str_to_date('9-13-1999','%m-%d-%Y');
%Y 4位的年份 %y 2位的年份
%m 月份(01,02....)
%c 月份(1,2,3....)
%d 日(01,02...)
%H 小时(24小时制)
%h 小时(12小时制)
%i 分钟(00,01,02...)
%s 秒(00,01,02)