交叉连接查询
这种查询方式基本不会使用, 原因就是这种查询方式得到的是两个表的乘积(笛卡儿集)
语法就是 select * from a,b;
内连接查询, 可以有效的去除笛卡尔集现象
内连接查询分为两类:
隐式内连接 select * from A,B where 条件
隐式连接使用别名: select * from A 别名 1,B 别名 2 where 别名 1.xx = 别名 2.xx;
显示内连接 select * from A inner join B on 条件 (inner 可以省略)
显示连接使用别名: select * from A 别名 1 inner join B 别名 2 on 别名 1.xx = 别名 2.xx
举例:
SELECT * FROM category c,product p WHERE c.cid=p.category_id;
外连接
外连接有两种方式, 一种是左外连接, 一种是右外连接
左外连接: select * from A left outer join B on 条件
右外连接: select * from A right out join B on 条件
左外连接就是左边的表的内容全部显示, 然后匹配右边的表, 如果右边的表匹配不到, 则空
右外连接就是右边的表的内容全部显示, 然后匹配左边的表, 如果左边的表匹配不到, 则空
总结:
内连接就是两个表的交集
左外连接就是左边表加两表交集
右外连接就是右边表加两表交集
子查询
子查询就是查询中还有查询, 就是一条 select 语句结果作为另外一条 select 语法的一部分(查询结果, 查询条件, 表等)
子查询的用处很多比如: 查询本公司工资最高的员工的详细信息
select * from emp where sal=max(sal)这个是错误的, 原因是聚合函数不可以用在条件中, 要想解决这个问题, 只能用子查询
select* from emp where sal=(select max(sal)from emp)
exists 关键字
select * from emp where exists(select max(sal) from emp)
这句话的意思是只要 (select max(sal) from emp) 有结果则执行 select * from emp, 否则不执行
子查询出现在 where 后是作为条件出现的
子查询出现在 from 之后是作为表存在的
作为表举例 select e.emono,e.ename from(select * from where deptno=30) e
还给表起了一个别名 e
作为条件有以下几种情况
单行单列: 可以使用 =,>,<,>=,<=,!=
多行单列 (集合) 可以用 All ANY IN not IN
单行多列(对象), 就是一行, 像一个对象一样什么属性都有
多行多列: 多行多列一直用在 from 后面作为表
单行单列举例: select * from emp where sal>(select avg(sal) from emp)
多行多列举例: select * from emp where sal> All(select sal from emp where deptno=10)
单行多列举例: select * from emp where(job,deptno,sal)IN(select job,deptno,sal from emp where ename='殷天正');(查询和殷天正一样工作, 工号, 工资的人的工作, 工号, 工资从 emp 表中)
来源: http://www.92to.com/bangong/2018/04-25/33655401.html