一关系数据记录查询
Ⅰ 并 union :把具有相同字段 数目和字段类型的表合并在一起,同时去掉重复的记录。
select * from t_cstudent
union
select * from t_mstudent
select * from t_cstudent
union all
select * from t_mstudent
Ⅱ笛卡尔积:就是把没有连接条件表关系返回的结果
笛卡尔积关系
列=表1字段数+表2字段数
行=表1记录数*表2记录数
①内连接(inner join):保留关系中所有匹配的数据记录,舍弃不匹配的数据记录
1自然连接:与自身进行连接,去掉重复的字段,新关系的字段数为1,
select e.ename employeename,e.job,l.ename loadername
from t_employee e inner join t_employee l
on e.mgr=l.empno;
select e.ename employeename,e.job,l.ename loadername
from t_employee e , t_employee l
where e.mgr=l.empno;
2等值连接:选择匹配字段值相等的数据记录
select e.empno,e.ename,e.job,d.ename,d.loc
from t_employee e inner join t_dept d
on e.deptno=d.deptno;
select e.empno,e.ename,e.job,d.ename,d.loc
from t_employee e , t_dept d
where e.deptno=d.deptno;
3不等连接:匹配字段不相等
select e.empno,e.ename,e.job,l.ename loadername
from t_employee e inner join t_employee l
on e.mgr=l.empno and e.empno>l.empno;
select e.empno,e.ename,e.job,l.ename loadername
from t_employee e ,t_employee l
where e.mgr=l.empno and e.empno>l.empno;
②外连接:不仅保留关系中所有匹配的数据记录,还会保留部分不匹配的数据记录
1左外连接 left outer join :除了选择相匹配的数据记录,还包含左边表中不匹配的数据记录
列=表1字段数+表2字段数
行=表1记录数*表2记录数--两表中不相等记录+左表未匹配记录数
select e.ename employeename,e.job,l.ename loadername
from t_employee e left join t_employee l
on e.mgr=l.empno;
比起自连接会存在没有对应值的雇员的记录
2右外连接 right outer join:除了选择相匹配的数据记录,还包含右边表中不匹配的数据记录
select e.empno,e.ename,e.job,d.ename,d.loc
from t_employee e right join t_dept d
on e.deptno=d.deptno;
3全外连接 full outer join:除了选择相匹配的数据记录,还包含左右两边表中不匹配的数据记录
③交叉连接
返回结果为多行单列子查询
in , exists:布尔类型
select * from t_employee
where deptno in (
select deptno from t_dept
);
select * from t_employee t
where not exists (
select * from t_dept
where deptno=c.deptno
);
any =any:与关键字in一样; >: 大于最小的; <:小于最大的
all >: 大于最大的; <:小于最小的
select ename,sal from t_employee
where sal>all(
select sal from t_employee
where job='manager'
);
select d.deptno,d.dname,d.loc,number,average
from t_dept d inner join (
select deptno dno,count(empno) number,avg(sal) average
from t_employee
group by deptno desc) employee
on d.deptno=employee.dno