数据库
having关键字
where后面只能写普通字段条件, 不能写聚合函数条件
聚合函数条件需要写在having关键字后面
having关键字需要结合group by分组查询使用
select job,count(*) from emp group by job having count(*)>1;
select job,count(*) c from emp group by job having c>1;
select deptno,avg(sal) a from emp group by deptno having a>2000;
select deptno,sum(sal) s from emp where mgr is not null group by deptno having s>5400;
select deptno,avg(sal) a from emp where sal between 1000 and 3000 group by deptno having a>=2000;
select job,count(*) c from emp where deptno in(1,2) group by job having c>1 order by c desc;
子查询(嵌套查询)
举例:
select avg(sal) from emp where deptno=1;
select * from emp where sal>(select avg(sal) from emp where deptno=1);
select max(sal) from emp;
select * from emp where sal=(select max(sal) from emp);
select min(sal) from emp where deptno=2;
select * from emp where sal>(select min(sal) from emp where deptno=2);
select job from emp where ename='孙悟空';
select * from emp where job=(select job from emp where ename='孙悟空') and ename!='孙悟空';
select min(sal) from emp; 得到最低工资
select deptno from emp where sal=(select min(sal) from emp)
select * from emp where deptno=(select deptno from emp where sal=(select min(sal) from emp) ) and sal!=(select min(sal) from emp);
select deptno from emp group by deptno order by count(*) desc limit 0,1;
select * from dept where deptno=(select deptno from emp group by deptno order by count(*) desc limit 0,1)
select job from emp group by job having count(*)=1;
select * from emp where job in(select job from emp group by job having count(*)=1);
关联关系
创建表时, 表和表之间存在的业务关系
有哪几种关系:
一对一: 有AB两张表,A表中一条数据对应B表中的一条数据, 同时B表中的一条数据也对应A表中的一条数据
一对多: 有AB两张表,A表中一条数据对应B表中的多条数据, 同时B表中的一条数据对应A表中的一条数据
多对多:有AB两张表,A表中一条数据对应B表中的多条数据, 同时B表中的一条数据也对应A表中的多条数据
外键: 用于建立关系的字段称为外键, 表和表之间的关系是通过外键字段建立好的.
关联查询
同时查询多张表数据的查询方式称为关联查询
有几种关联查询方式?
等值连接
内连接
外连接
关联查询之等值连接
格式:
select * from A,B where A.x=B.x(关联关系) and A.age>30;
举例:
select ename,dname from emp e,dept d where e.deptno=d.deptno;
关联查询之内连接
格式: select * from A join B on A.x=B.x(关联关系) where A.age>30;
等值连接和内连接查询到的数据是一样的数据,都是两张表的交集数据
举例:
select ename,dname from emp e join dept d on e.deptno=d.deptno;
select ename,dname,loc from emp e join dept d on e.deptno=d.deptno where e.deptno=1 and sal>2000;
关联查询之外连接
外连接 查询到的是一张表的全部数据和另外一张表的交集数据
格式:
select * from A left/right join B on A.x=B.x(关联关系) where A.age>30;
举例
select dname,ename from emp e right join dept d on e.deptno=d.deptno;
insert into emp(empno,ename,sal) values(100,'Tom',500) select e.*,dname from emp e left join dept d on e.deptno=d.deptno;
关联查询总结
如果查询的是两个表的交集数据,则使用等值连接或内连接(推荐)
如果查询的数据是一张表的全部和另外一张表的交集则使用外连接
文章转载自沉默寡言左家琦,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




