您的位置:首页 > 数据库 > MySQL

MySQL学习笔记(二)

2017-09-07 10:27 459 查看
MySQL学习笔记(二):

此笔记所用测试数据库地址:点击打开链接

一、常用函数

1.lower(字段):把字段或字符串转换成小写 

  select userId,lower(username) from user

  

  upper(字段):把字段或字符串转换成大写 

  select userId,upper(username) from user

2.concat(字段1,字段2,...):连接两个字段或字符串

  select concat(username,password) from user

3.length(字段):求字段的长度

  select length(password) from user

4.substr(字段,start,length):截取字段

  select userId,substr(username,1,3) from user

二、分组函数(重点)

1.avg(字段):计算查询结果的平均值

  select avg(sal) from emp

2.max():

  select max(sal) from emp

3.min():

  select min(sal) from emp

4.sum():

  select sum(sal) from emp

5.count():

  select count(deptno) from emp

三、对查询结果分组

以deptno分组后查询deptno:

select deptno from emp group by deptno



以deptno分组后查询deptno和sal的平均值:

select deptno,avg(sal) from emp group by deptno

以deptno分组后查询deptno和sal的和:

select deptno,sum(sal) from emp group by deptno

综合示例:

select deptno 分组号,avg(sal) 平均工资,sum(sal) 总工资,max(sal) 最高工资,min(sal) 最低工资,count(deptno) 总人数 from emp group by deptno



组函数加条件用having,不能用where:

select deptno 组号,job 职位,avg(sal) 平均工资,sum(sal) 总工资,max(sal) 最高工资,min(sal) 最低工资,count(deptno) 总人数 from emp group by job  having avg(sal) > 2000



分组筛选查询后降序排列:

select deptno 分组号,avg(sal) 平均工资,sum(sal) 总工资,max(sal) 最高工资,min(sal) 最低工资,count(deptno) 总人数 from emp group by deptno  having avg(sal) > 2000 order by deptno desc

四、子查询(查询结果是一张临时的表)

e是临时表的别名:

select * from (select * from emp) e

查询工资大于平均工资:

select * from emp where sal > (select avg(sal) from emp) order by sal

子查询结合in的使用:

select * from emp where empno in (select empno from emp where empno=7521 or empno=7698 or empno=7369)



五、连表语句(多表查询):重点(必需条件:外键,相同字段)

e,d是别名,where是普通条件:

select e.*,d.dname,d.loc from emp e,dept d where e.deptno=d.deptno

inner join(on是连表的条件,常用):

select e.*,d.dname,d.loc from emp e inner join dept d on e.deptno=d.deptno



其他:

inner join(等值连接) 只返回两个表中联结字段相等的行 

left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 

select e.*,d.dname,d.loc from emp e left join dept d on e.deptno=d.deptno

right join(右联接) 返回包括右表中的所有记录和
8d52
左表中联结字段相等的记录

select e.*,d.dname,d.loc from emp e right join dept d on e.deptno=d.deptno



六、分页查询

mysql关键字:limit start,length

查询第1条到第5条数据:select * from emp limit 0,5

查询第5条到第10条数据:select * from emp limit 5,5

查询第10条到第15条数据:select * from emp limit 10,5
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: