聚和函数
avg/count/max/min/sum
count(*)
将也对NULL计数,count(column)
计数时将不考虑NULL
count(all column)
#默认all行为
count(distinct column)
#不统计重复列
all/distinct
对avg/min/max/sum行为同理
字符函数
concat() # 字符连接
select concat(username, '_', pid) as uname_p from users;
concat_ws() # 使用指定分隔符连接字符
select concat_ws('_', username, pid) as uname_p from user; # concat_ws()第一个参数指定分隔符
format() #数字格式化,转为为字符
select format(123.456,1); # -->'123.46'
lower()/upper()
select lower('asDF'); # -->'asdf'
left()/right()
select upper(left('binggo', 4)); # --> 'BING',可以函数嵌套
length() # 长度
ltrim()/rtrim()/trim() # 删除空格
trim(leading '-' from '--bing---') # --> 'bing---'
trim(trailing '-' from '--bing---') # --> '--bing'
trim(both '-' from '--bing---') # 'bing'
replace('--bin-g--', '-' '') # --> 'bing'
substring('binggo', 5,2) # --> go
substring('binggo', 5) # --> go
substring('binggo', -2) # --> go
select * from test where first_name like '%1%' escape '1'; # 只匹配tom%,而不匹配A,C
# %:任意个字符
# _:任意一个字符
数值运算
cell(3.01) # --> 4
float(3.88) # --> 3
select 3/4 # --> 0.75
select 3 div 4 # -->0,整除
select 3 mod 4 # -->3
power()
round()/truncate() # 四舍五入/截断
比较运算符
select 1 [not] bewteen 0 and 3; # --> 1[0]
select 1 in(0,1,2,3); # -->1
select * from test where username is [not] null; # is null的使用
时间日期
now(); # 2017-12-03 10:23:15
curdate(); # 2017-12-03
curtime(); # 10:23:15
select data_add('2017-12-02', interval -10 day); # week/year
select datadiff('2016-12-03', curdate()); # -->-365
select date_format('2017-12-03', '%m/%d/%Y'); # -->12/03/2017
信息函数
connection_id() #不同用户id都不一样
last_insert_id() # 表必须有auto_increment的字段,不一定叫id;如果一次insert多条,返回的是多条记录的第一个id.
聚合函数
# md5();
# password();
set password=password('123123'); #修改当前用户的密码为123123
其他
select ifnull(null, 0); #将null值设置为0
select if(true, 1, 0); #if(expr,1,0),expr为True返回1,否则返回0
自定义函数
create function foo(n1 smallint unsigned, n2 smllint unsigned)
returns float(10,4) unsigned
return (n1+n2)/2; # 创建函数
select foo(10, 11) # 调用函数
drop function foo; # 删除函数foo
delimiter // # 修改结束符号为//
create function foo(uname varchar(20)) #创建复合语句的函数
returns smallint unsigned
begin
insert user1(username) values(uname);
select last_insert_id();
end//