SQL–Oracle 区分外连接内连接
一、表解构和数据
INSERT INTO "XIELONG"."S_EMP_TEST" (ID, NAME) VALUES ('1', 'a')
INSERT INTO "XIELONG"."S_EMP_TEST" (ID, NAME, M_ID) VALUES ('2', 'b', '1')
INSERT INTO "XIELONG"."S_EMP_TEST" (ID, NAME, M_ID) VALUES ('3', 'c', '1')
INSERT INTO "XIELONG"."S_EMP_TEST" (ID, NAME, M_ID) VALUES ('4', 'd', '2')
INSERT INTO "XIELONG"."S_EMP_TEST" (ID, NAME, M_ID) VALUES ('5', 'e', '2')
二、内连接和外连接定义
内连接:
- 定义:最常用也是最重要的结合就是等值连接,也被称为内部结合、内连接。通常利用通用字段结合两个表,而这个字段通常是每个表里的主键。
- 用途:需要取出两张或以上的表格的数据,需要用到内连接。
- 语法:
--1、where的方式
SELECT * FROM S_EMP E, S_DEPT D WHERE E.DEPT_ID=D.ID;
--2、join on
SELECT * FROM S_EMP E join S_DEPT D on E.DEPT_ID=D.ID;
--3、inner join on
SELECT * FROM S_EMP E inner join S_DEPT D on E.DEPT_ID=D.ID;
- 案例:
--内连接 两张表的数据
select * from s_emp_test e1, s_emp_test e2 where e1.id=e2.m_id;
--内连接 一张表的数据 有重复
select e1.* from s_emp_test e1, s_emp_test e2 where e1.id=e2.m_id;
外连接:
-
定义
- 外连接的结果集, 等于内连接的结果集,加上匹配不上的记录!
- 通过在字段后面添加(+), 来完成外连接操作。
- 外连接会返回一个表里的全部记录,即使对应的记录在第二个表里不存在。加号(+)
用于在查询里表示外部结合,放在WHERE子句里表名的后面,具有加号的表是没有匹配记 录的表.在很多实现里。
-
分类:外连接被划分为左外连接、右外连接和全外连接。
-
语法:
外部结合的-般语法如下所示
FROM TABLEl
{RIGHT | LEFT | FULL} [OUTER] JOIN
ON TABLE2
Oracle 的语法是
From TABLE1 , TABLE2 [,TABLE3]
WHERE TABLE1.COLUMN_NAME[(+)] = TABLE2.COLUMN_NAME[(+)]
[ AND TABLE1.COLUMN_NAME[(+)] = TABLE3.COLUMN_NAME[(+)] ]
- 实例:
- 表结构:如上图表s_emp_test的数据
- 外连接实例:
-- 外连接 (+)在=前 e2表中的数据全部展示出来,不符合条件的用NULL补充到e1
select * from s_emp_test e1, s_emp_test e2 where e1.m_id(+)=e2.id;
-- 外连接 (+)在=前 等同于如下右连接 e2为主表 e2表的数据全部展示,e1表用NULL补足
select * from s_emp_test e1 right join s_emp_test e2 on e1.m_id=e2.id;
-- 外连接 (+)在=和字段后 e1表中的数据全部展示出来,不符合条件的用NULL补充到e2
select * from s_emp_test e1, s_emp_test e2 where e1.m_id=e2.id(+);
--外连接 (+)在=和字段后 等同于如下左连接 e1为主表 e1表的数据全部展示,e2表用NULL补足
select * from s_emp_test e1 left join s_emp_test e2 on e1.m_id=e2.id(+);
-- 查询普通员工 --
-- 左连接:查询普通员工(非领导的员工信息)根据上面的外连接(+)在后面,外连接补NULL,然后用e2表的ID is null 取出员工号
select * from s_emp_test e1, s_emp_test e2 where e1.id=e2.m_id(+) and e2.id is null;
-- 右连接:查询普通员工的另一种方式
select * from s_emp_test e1, s_emp_test e2 where e1.m_id(+)=e2.id and e1.id is null;
--注意用 where 而不是 and 用and去并集 不符合要求
select * from s_emp_test e1 right join s_emp_test e2 on e1.m_id=e2.id where e1.id is null;
-- 查询领导 --
-- 右连接
select distinct e2.* from s_emp_test e1 right join s_emp_test e2 on e1.m_id = e2.id where e1.m_id is not null;
-- 左连接
select distinct e1.* from s_emp_test e2 left join s_emp_test e1 on e2.m_id = e1.id where e2.m_id is not null;
--全外连接 左连接和有链接的结果取数学合集(去掉重复)
-- FULL JOIN 或 FULL OUTER JOIN
select * from s_emp_test e1 FULL JOIN s_emp_test e2 on e1.m_id=e2.id;