SQL教程——常见函数之单行函数
本教程中所使用的数据库的建表语句都在“SQL教程——索引”这篇文章中,点击链接直达:索引&建表语句
摘要:本文主要介绍SQL的常见函数中的单行函数
常见函数
概念:类似于java中的方法,将一组逻辑语句封装在方法体中,对外暴露方法名
好处:1、隐藏了实现的细节 2、提高了代码的重用性
调用:select 函数名(实参列表)【from 表】;
特点:1、函数名(叫什么)
2、函数功能(干什么)
分类:
1、单行函数 如 concat、length、 ifnull
2、分组函数 做统计使用,又称为统计函数、聚合函数、组函数
单行函数
又细分为字符函数、数学函数、日期函数、其它函数【补充】、流程控制函数【补充】
1、字符函数(参数为字符)
select length('john'); 输出4select length('发送happy'); 输出8 与mysql默认字符集有关,一个汉字占两个长度#length函数比较特殊,mysql中只有它是按的字节长度,其它函数基本都按字符。select concat(last_name, '_', first_name) 姓名 from employees;select upper('john');select lower('JOHN');select concat(upper(last_name), lower(first_name)) 姓名 from employees;substr、substringselect substr('李莫愁爱上了陆展元', 6) out_put; #索引从6开始! 输出:了陆展元select substr('李莫愁爱上了陆展元', 1,3) out_put; #包括1和3位置上的字符 输出:李莫愁select instr('杨不悔爱上了殷六侠','殷六侠') as out_put; #返回后边的字符串第一次在前边的字符串中出现的索引。select length(trim(' 张翠山 ')) as out_put;select trim('a' from 'aaa行aaa好aaa') as out_put; #把a当做空格select lpad('殷素素', 10, '*') as out_put; #用指定字符进行右填充select replace('张无忌爱上了周芷若', '周芷若', '赵敏') as out_put;
2、数学函数(参数为数值)
select round(-1.55); #输出-2select round(-1.555, 2); #输出 -1.56select ceil(1.02); #向上取整select floor(1.02); #向下取整select truncate(1.69999, 2); #小数点后截取2位select mod(-10, 3); #等价于-10%3 结果的符号等与第一个数的符号select rand(); #获取随机数,返回0-1之间的小数
3、日期函数(参数为类型)
select now(); #输出:2019-12-10 19:06:48select curdate(); #输出:2019-12-10select curtime(); #输出:19:06:48select year(now()) 年;select year(hiredate) 年 from employees;select month(now()) 月;select monthname(now()) 月; #输出:Decemberselect str_to_date:将日期格式的字符串转换成指定格式的日期str_to_date('9-13-1999', '%m-%d-%Y');

select str_to_date('1998-3-2', '%Y-%c-%d') as out_put;#查询入职日期为1992-4-3的员工信息select * from employees where hiredate = '1992-4-3';select * from employees where hiredate = str_to_date('4-3 1992', '%c-%d %Y');date_format:将日期转换成字符串select date_format(now(), '%Y年%m月%d日') as out_put;#查询有奖金的员工名和入职日期(xx月/xx日 xx年)select last_name, date_format(hiredate, '%m月/%d日 %y年') 入职日期 from employees;#计算现在的日期和一个给定日期的差值(天数)select datediff(now(), '2016-6-9');
4、其它函数
select version();select database(); #输出:root@localhostselect user();select md5(); #输出1bceb9ca798ffaa9151ac58e38595308
5、流程控制函数
select if(10>5, 'big', 'small'); #java三目运算符select last_name, commission_pct, if(commission_pct is null, '没奖金,呵呵', '有奖金,嘻嘻') 备注 from employees;select salary 原始工资, department_id,case department_idwhen 30 then salary*1.1when 40 then salary*1.2when 50 then salary*1.3else salaryend as 新工资from employees; #case 语句要在case与end之间 语法类似于java的switch caseselect salary,casewhen salary>20000 then 'A'when salary>15000 then 'B'when salary>10000 then 'C'else 'D'end as 工资级别from employees;
总结:
1、字符函数:lengthconcatsubstrinstrtrimupperlowerlpadrpadreplace2、数学函数roundceilfloortruncatemodrand3、日期函数nowcurdatecurtimeyearmonthmonthnamedayhourminutesecondstr_to_datedate_formatdatediff4、其它函数versiondatabaseusermd55、流程控制函数ifcase
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
