数据库连接查询
--部门表
createtable department(idnumberprimarykey,namevarchar2(30));
--员工表
createtable employee( idnumberprimarykey, namevarchar2(30)notnull, salary number(6,2), title varchar2(30), manager number, deptidnumber);
--插入数据
insertinto department values(1,'人力资源');
insertinto department values(2,'开发中心');
insertinto department values(3,'总裁室');
insertinto department values(4,'运维中心');
insertinto employee values(4,'赵六',9000,'项目经理',null,2);
insertinto employee values(3,'王五',7000,'项目组长',4,2);
insertinto employee values(1,'张三',6000,'程序员',3,2);
insertinto employee values(2,'李四',7000,'HR',4,1);
droptable department;
droptable employee;
- 内连接(自然连接) join(inner join) on
1.笛卡尔集中满足on条件的记录,当没有限制on条件时,为两个表的笛卡尔集
2.和自然连接类似,使用where限制
3.只有满足限制条件的记录才会返回到结果集中
select * from employee,department ; --也是内连接的一种形式
select * from employee inner join department on 1=1;
--上两sql等价
select * from employee e,department d where e.deptid=d.id;
select * from employee e join department d on e.deptid=d.id;
--上两sql等价
1.同一个表当两个不同的两个表,两个表做连接。2.一般表的两个字段间有上下级关系
2.内连接的特殊形式
查找员工的上级 (查不出没有上级的人物)
select s1.id,s1.name,s2.name as manager from employee s1,employee s2 where (s1.manager=s2.id);
- 外连接 (左、右、全连接)
- 左连接
left join(left out join)
1.在右表中没有满足on的限制条件的记录也返回的结果集,即会返回左表的所有行。
- 右连接
right join(right out join)
1.在左表中没有满足on的限制条件的记录也返回的结果集,即会返回右表的所有行。
- 全连接
full join (full out join)
1.在左表中和右表中没有满足限制条件的记录都返回到结果集中
select * from employee e full join department d on e.deptid=d.id;
- 交叉连接
1.没有where条件,返回两个表的笛卡儿积
2.等价于没有限制条件的内连接
select * from employee e cross join department ;
select * from employee,department ;
select * from employee inner join department on 1=1;
上面三条等价
select * from employee e cross join department d where e.deptid=d.id;
select * from employee e,department d where e.deptid=d.id ;
select * from employee e inner join department d on e.deptid=d.id ;
上面三条等价