多表查询(连接查询,库表查询)
多张表联合索引
没有限制条件的关联——笛卡尔集-cross join
select ename, dname from emp, dept; 等价于 select ename, dname from emp cross join dept;
内连接
A表与B表连接,只查询匹配记录
等值连接:inner-join
#查询每一个员工所在部门的名称,要求最终显示员工姓名和对应的部门名称
select ename, dname from emp inner join dept on emp.deptno = dept.deptno
非等值连接
查询员工姓名,薪水,薪水对应等级
方法一: select e.ename, esal, e.grade from emp as e inner join salgrade as s on e.sal >= s.losal and e.sal <= s.hisal; 方法二: select ename, sal, grade from emp as e inner join salgrade as s on e.sal between s.losal and s.hisal
自连接
select emp.ename empname, emp.empno, empmgr.ename as marname, empmgr.empno as mgrno from emp inner join emp as empmgr on emp.mgr = empmgr.empno
外连接
左连接
两张表联合查询,一张表为主,关联另外一张表的匹配字段,如果没有匹配上,在这个主表的连接显示上显示null占位
练习:查询所有杀手和杀手中被杀清单上的信息名单
select user1.user_name, user1.over, user2.over from user1 left join user2 on user1.user_name = user2.user_name
#查询没有在被杀名单上的杀手信息
select user1.user_name, user1.over, user2.over from user1 left join user2 on user1.user_name = user2.user_name where user2.over is null;
右连接
查询被杀名单以及上面的杀手信息
select user2.user_name, user2.over, user1.over from user1 right join user2 on user1.user_name = user2.user_name
查询被杀名单中不是杀手的信息
select user2.user_name, user2.over, user1.over from user1 right join user2 on user1.user_name = user2.user_name where user1.over is null
注意:where条件跟的user1.over是select后面查出来以后的值user1.over
全连接(不要求掌握,掌握了很强)-full join
定义:包含左,右两个表的全部行,不管另外一个表中是否存在与他们匹配的行。
full-join没有直接实现的语句,需要通过来拟合表结构实现
#查询杀手清单上的信息,杀手在被杀清单上的信息,被杀清单上的信息,被杀清单上的杀手信息
select user1.user_name, user1.over, user2.over from user1 left join user2 on user1.user_name = user2.user_name union all select user2.user_name, user2.over, user1.over from user1 right join user2 on user1.user_name = user2.user_name
合并结果集
合并结果集的时候,每个查询表中的字段个数要相同
union—合并相同的数据
select ename, job from emp where job = ‘MANAGER’ union select ename, job from emp where job = ‘CLERK’;
union all 不会合并相同的数据
select ename, job from emp where job = ‘MANAGER’ union all select ename, job from emp where job = ‘CLERK’;