本文列举数据库的多表关联查询及实际使用,以员工表和部门表作为举例: 部门表:dept 员工表:emp点击查看创建部门表sql
create table `dept` (
`deptno` int(2) not null,
`dname` varchar(14),
`loc` varchar(13),
primary key (`deptno`)
);点击查看创建员工表sql
create table `emp` (
`empno` int(4) not null,
`ename` varchar(10),
`job` varchar(9),
`mgr` int(4),
`hiredate` date,
`sal` int(7),
`comm` int(7),
`deptno` int(2),
primary key (`empno`),
index `fk_deptno`(`deptno`),
constraint `fk_deptno` foreign key (`deptno`) references `dept` (`deptno`) on delete restrict on update restrict
);SQL关联查询/连接查询
一、内连接
select ename,dname from emp inner join dept on emp.deptno=dept.deptno;
二、左外连接(left join 前为主表,后为从表,遍历主表中的每一条记录查询)
select dname,ename from dept left join emp on dept.deptno=emp.deptno;
select ename,dname from emp left join dept on emp.deptno=dept.deptno;
三、右外连接(right join 前为从表,后为主表,遍历主表中的每一条记录查询)
select dname,ename from emp right join dept on dept.deptno=emp.deptno;
自连接
select e.ename 员工,p.ename 上级领导 from emp e left join emp p on e.mgr=p.empno;
子查询/嵌套查询
单行子查询:子查询的结果只有一条
select * from emp where deptno=(select deptno from emp where ename='scott');
多行子查询:子查询的结果有多条
select * from emp where sal in (select sal from emp where deptno=10) and deptno!=10;