一、使用MySQL特有的函数!
1》到年底还有几天
select datediff(‘2014-12-31‘,‘2014-6-21‘);//此函数用于计算日期只差
select datediff(‘2014-12-31‘,now());//函数now为当前日期
2》年月日
select year(now());
select moth(now());
select day(now());
3》substring(str,position[,length])
从str的position开始,取length个字符
索引从1开始。
code:
select substring(‘http://localhost:8080/day12/mysql‘,29);//mysql
select substring(‘http://localhost:8080/day12/mysql‘,29,2);//my
4》format
保留小数点后2位,四舍五入
select fromat(3.141596535,2);
5》向下取整
select floor(3.14);
select floor(-3.14);
select floor(3.54);
select floor(-3.54);
6》向上取整
select ceiling(3.14);
7》取随机值
rand();返回一个随机浮点值 v ,范围在 0 到1 之间
select format(rand(),2);
取1-6之间的随机整数值:
select floor(rand()*6)+1;//6代表取值之间的数字
8》随机产生‘a‘-‘z‘之间的随机字符
1)查询‘a‘-‘z‘对应的Unicode值
select ascii(‘a‘);
select ascii(‘z‘);
2)产生97-122之间的随机整数
select floor(rand()*26)+97;
3)产生97-122之间对应的字符
select char(select floor(rand()*26)+97);
9》利用MySQL的函数,对密码‘123456‘进行MD5加密
code:
select md5(‘123456‘);
二、扩展知识——MySQL特有流程控制函数:
1》if(value,第一值,第二值);
value为真,取第一值,否则取第二值
类似于Java中的三目运算符
code:
将5000元(含)以上的员工标识为"高薪",否则标识为"起薪"
select if(salary>=5000,‘高薪‘,‘起薪‘)
from user;
2》ifnull(value1,value2)
value1为NULL,用value2替代
code:
将薪水为NULL的员工标识为"无薪"
select name as 员工,ifnull(salary,‘无薪‘) as 薪水情况
from user;
3》case when [value] then [result1] else [result2] end;
当value表达式的值为true时,取result1的值,否则取result2的值(if...else...)
将5000元(含)以上的员工标识为"高薪",否则标识为"起薪"
select
case when salary>=5000 then ‘高薪‘
else ‘起薪‘ end
from user;
4) case [express] when [value1] then [result1] when [value2] then [result2] else [result3] end;
当express满足value1时,取result1的值,满足value2时,取result2的值,否则取result3的值(switch...case..)
将7000元的员工标识为"高薪",6000元的员工标识为"中薪",5000元则标识为"起薪",否则标识为"低薪"
select
case salary
when 7000 then ‘高薪‘
when 6000 then ‘中薪‘
when 5000 then ‘起薪‘
else ‘低薪‘ end
from user;
课堂练习:
1》查询相同性别的员工总人数>2的工资综合,并按工资综合降序排列
select gender as 性别, count(*) as 员工数
from user
group by gender
having count(*)>3
order by sum(salary) desc;
2》将性别为男的员工工资-1000,性别为女的员工工资+1000,在一条SQL上完成
方法一:
select id, name, gender as 性别,case when gender=‘female‘ then salary+1000 else salary-1000 end as 工资
from user;
方法二:
select id,name,gender as 性别, if(gender=‘femal‘,salary+1000,salary-1000) as 工资 from user;
方法三:
select id,name,gender as 性别, case gender when ‘female‘ then salary+1000 else salary-1000 end as 工资 from user;
总结:
count函数,sum函数等:
1》没有group by 进行分组的时候将整个表看为一组,进行计算、统计;
2》有group by 进行分组的时候,以分后的组为依据,进行计算和统计。
原文:http://www.cnblogs.com/SkyGood/p/4005012.html