Mysql数据库_DML_常用函数.sql

来源:互联网 发布:剑三破军道姑捏脸数据 编辑:程序博客网 时间:2024/05/21 11:34
/*
//concat连接
*/
select concat(name,description) from tb_dept;
/*
//查询的时候转大小写
*/
select upper(name) from tb_emp where empno=8000;
select lower(name) from tb_emp where empno=8000;
/*
//返回字符串的长度
*/
select length(name) from tb_emp where empno=8000;
/*
//取字符串的从第一位开始前两位
*/
select substr(name,1,2) from tb_emp where empno=8000;
/*
//_____________________________________________________________---
//日期和时间函数
*/
select now();--当前时间
#查询入职时间是1980年的人
select * from tb_emp
where year(hiredate) = 1980;
#查询入职时间是1980年2月的人
select * from tb_emp
where year(hiredate) = 1980
and month(hiredate) = 2;
/*
//插入时间
*/
insert into tb_emp (empno,name,job,hiredate,sal)
values(8001,'周杰伦','天王','2011-12-14',600);


insert into tb_emp (empno,name,job,hiredate,sal)
values(8001,'蔡依林','小天王',now(),600);




/*
//**************************************************************
//流程函数
*/
select ename,job,sal,comm,  --comm是原定奖金
    case comm
when comm is null then 100 --当奖金是0时就给100
else comm
end as '奖金'
from tb_emp;


/*
//#ifnull 函数
//
*/
#如果字段不为null,则取第二个值,如果为空,取第三个值
select comm,if(comm,comm+200,100) from tb_emp;
#如果字段不为null,则直接返回该值,如果为空,取第二个值
select comm,ifnull(comm,100) from tb_emp;






/*
//聚合函数,也叫组合函数
*/
select AVG(sal) from tb_emp; --平均工资
select SUM(sal) from tb_emp; --总工资
select MAX(sal) from tb_emp; --最大工资
select MIN(sal) from tb_emp; --最小工资


select SUM(sal) as 工资总额,MAX(sal) as 最高工资,
       MIN(sal) as 最低工资,AVG(sal) as 平均工资
from tb_emp where dept=10;


select count(*) from tb_emp;--count不统计null,统计的是记录数
select count(comm) from tb_emp;


select count(deptno) from tb_emp;
select count( distinct deptno) from tb_emp;--部门有重复,出去重复


select AVG(comm) from tb_emp;--组函数忽略空值


/*
//group by  子句
*/


select deptno,AVG(sal) from tb_emp group by deptno;--每个部门的平均工资
select deptno,count(*) from tb_emp group by deptno;--每个部门的员工数
select deptno,AVG(sal),MAX(sal),MIN(sal),COUNT(1)
from tb_emp
group by deptno;--根据部门编号分组


select deptno,job,AVG(sal) from tb_emp where deptno=10 group by deptno;


select AVG(sal) from tb_emp where deptno=10 group by deptno,job;--每个部门每个职位的平均工资
/*
//where和having都是用来做条件限定的,但是having只能在group by之后
//where子句中不能使用聚合函数
//having子句可以使用聚合函数
*/
select deptno,AVG(sal),MAX(sal),MIN(sal),COUNT(1)
from tb_emp
group by deptno
having AVG(sal) > 2000
order by AVG(sal) asc;


/*
//limit,常用来分页
//select ... limit offset_start,row_count;
//offset_start:第一个返回记录行的偏移量.默认为0
//row_count:要返回记录的最大数目
*/
select * from tb_emp limit 5; --检索前5个记录
select * from tb_emp limit 5,10; --检索记录行6-15











































0 0