数据库MySql学习之旅 六
DQL(data query language)的学习?
二、 数学函数
1、round 四舍五入
select round(1.65);
select round(1.567, 2);
2、ceil 向上取整,返回大于等于该参数的最小整数
select ceil(1.002)
3、floor 向下取整,返回小于等于该参数的最大整数
select floor(2.3);
4、truncate 截断
select truncate(1.788888,1);
5、mod取余
select mod(10,3); #被除数为正数,结果为正,否则为负数
select 10%3;
三、日期函数
1、now 返回当前系统日期+时间
select NOW();
2、curdate 返回当前系统日期,不包含时间
select curdate();
3、curtime 返回当前时间,不包含日期
select curtime();
4、获取指定的部分、年、月、日、小时、分钟、秒
select YEAR(now()) 年;
select YEAR('1998-1-1') 年;
select MONTH(NOW()) 月;
select MONTHNAME(NOW()) 月;
5、str_to_date 将字符通过指定的格式转换为日期
select str_to_date('1998-3-2','%Y-%c-%d') as out_put;
实例:查询入职日期为1992-4-3的员工信息
select * from employee where hiredate = '1992-4-3';
select * from employee where hiredate = str_to_date('4-3 1992', %c-%d %Y');
6、date_format 将日期转换为字符
select date_format(now(), '%y年%m月%d日') as output;
实例:查询有奖金的员工名和入职日期(xx月/xx日 xx年
select last_name, date_format(hire_date, '%m月/ %d日 %Y年‘) 入职日期 from employees where commision_pct is not null;
四、其他函数
select version();
select database();
select user();
五、流程控制函数
1、if函数: if else 的效果
select if(10>5,’大‘,’小‘);
select last_name, commision_pct, if(commission_pct is null, '没奖金’,'有奖金') 备注 from employees;
2、case 函数的使用:switch case的效果
case 要判断的字段或者表达式
when 常量1 then 要显示的值1或语句1;
when 常量2 then 要显示的值2或语句2;
else 要显示的值n或语句n;
end
案例:查询员工的工资,要求
部门号=30,显的工资为1.1倍
部门号=40,显的工资为1.2倍
部门号=40,显的工资为1.3倍
其他部门,显示的工资为原工资
select salary, 原始工资
select salary 原始工资, department_id,
case department_id
when 30 then salary*1.1
when 40 then salary*1.2
when 50 then salary*1.3
else salary
end as 新工资
from employees;
3、case 函数的使用二:类似于 多重if;
case
when 条件1 then 要显示的值1或语句1;
when 条件2 then 要现实的值2或语句2;
...
else 要显示的值n或语句n
end
案例: 查询员工的工资情况,如果工资大于20000,显示A级别
如果工资大于150000,显示B级别
如果工资大于10000,显示C级别
否则,显示D级别
select salary
case
when salary>20000 then 'A'
when salary>15000 then 'B;
when salary>10000 then 'C'
else 'D'
end as 工资级别
from employees;

浙公网安备 33010602011771号