MySQL学习笔记(二)

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(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录

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




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值