sql数据库html
5. select 查看结果集中的哪一个列,或列的计算结果 1. from 须要从哪一个数据表检索数据 2. where 过滤表中数据的条件 3. group by 如何将上面过滤的数据分组 4. having 对已分组的数据进行过滤的条件 6. order by 按照不一样排序方式返回数据
did | dname | dmgr |
---|---|---|
1 | 销售部 | 1001 |
2 | 研发部 | 1005 |
3 | 服务部 | 1008 |
id | name | gender | age | salary | dno | mgrid |
---|---|---|---|---|---|---|
1001 | 赵伟 | 男 | 38 | 6000 | 1 | |
1002 | 李萍兰 | 女 | 26 | 3000 | 1 | 1001 |
1003 | 秦晓 | 女 | 30 | 4000 | 1 | 1001 |
1004 | 赵晓辉 | 男 | 32 | 4200 | 1001 | |
1005 | 张岚 | 男 | 40 | 8000 | 2 | |
1006 | 李秋平 | 女 | 24 | 4000 | 2 | 1002 |
1007 | 顾世刚 | 男 | 30 | 6000 | 2 | 1002 |
1008 | 段大宇 | 男 | 36 | 5000 | 3 |
select column_list from table_name1,table_name2 #表之间经过逗号隔开 where codition #表之间的链接条件
select column_list from table_name1 [inner] join table_name2 #表之间的链接经过 join实现 on condition; #表之间的链接条件 [...n]
外链接: 指表链接时除了返回符合链接条件的数据外,同时返回不符合链接条件的数据git
全外链接:github
语法:web
select column_list from table_name1 [left|right|full] [outer] join table_name2 #表之间的链接条件经过 xx join 实现 on condition #表之间的链接条件 [...n]
指对同一个表的链接,要执行一个内链接,必须使用不一样的别名来区分sql
select e1.name 员工姓名,e2.name 上级主管 from emp e1,emp e2 where e1.mgrid=e2.id
在多表查询时,若是没有链接条件,则一个表的全部行将会和另外一个表的全部行都会进行链接,链接的结果称为笛卡尔积数据库
select column_list from table_name1,table_name2[...n]
select column_list from table_name1 cross join table_name2[...n]
在前面使用的查询语句都是只包含一条select语句,而有些状况下依靠单条select语句没法完成查询要求canvas
这时候须要在select语句中内部嵌入另外的select语句,这条嵌入的select语句称为子查询ruby
子查询除了能够应用到select语句中,也能够应用到insert、update、delete语句中markdown
单行子查询不向外部的SQL语句返回结果,或者只返回一行app
单行子查询可应用于select语句的where字句、having字句中
- 查询年龄最小的员工信息 select * from emp where age=(select min(age) from emp) 结果:查询到一条 - 查询大于最小年龄的员工信息 select * from emp where age>(select min(age) from emp) 结果:查询到多条信息
- 查询部门员工平均年龄小于全部员工平均年龄的部门和该部门员工平均年龄 select dno 部门编号,avg(age) 平均年龄 from emp group by dno having avg(age)<(select avg(age) from emp)
多行子查询一般返回一条或多条记录,多行子查询结果用于where语句时
判断可使用in、any、all操做符
-查询负责管理其余员工的员工信息 --in select * from emp where id in (select mgrid from emp where mgrid is not null) - 查询年龄大于全部部门最大年龄的员工信息 --all select * from emp where age > all(select max(age) from emp group by dno) - 查询年龄大于任意部门最大年龄的员工信息 --any select * from emp where age > any(select max(age) from emp group by dno)
子查询中引用父查询信息,称为关联子查询
关联子查询对于外部查询中的每一行都会运行一次
-查询每一个部门年龄最小员工 select * from emp o where age=(select min(age) from emp i where i.dno=o.dno) -查询负责管理其余员工的员工信息 select * from emp e1 where exists (select 1 from emp e2 where e2.mgrid=e1.id) -查询不负责管理其余员工的员工信息 select * from emp e1 where not exists (select 1 from emp e2 where e2.mgrid=e1.id)
操做符 | 说明 |
---|---|
union all | 并运算。返回各个查询检索出的全部行,包括重复行 |
union | 并运算。返回各个查询检索出的全部行,不包括重复行 |
intersect | 交运算。返回两个查询检索的共有行 |
except | 差运算。从左查询中返回右查询没有找到的全部的全部非重复值 |
union all 操做只合并结果集,不去除重复数据
- 查询全部产品 select * from prod1 union all select * from prod2 结果可能含有重复行
union操做合并结果集后去除重复数据
-查询全部产品 select * from prod1 union select * from prod2 结果:无重复行
intersect操做返回结果集间的交集,也就是共有部分
-查询两个产品表的共有产品 select * from prod1 intersect select * from prod3 结果:返回两表共有行