-- ###################join操作###########################
-- 1、内连接
/*
1)内连接求的是多张表的交集
2)内连接又分为两种
隐式内连接
显式内连接
*/
select *
from teacher;
show tables;
create external table course
(
cid string,
cname string,
tid string
) row format delimited fields terminated by '\t';
load data local inpath '/export/data/course.txt' overwrite into table course;
select *
from course;
-- 笛卡尔积
select *
from teacher,
course;
-- 1.1 查询每一个老师所教授的课程
-- 隐式内连接
select *
from teacher t,
course c
where t.tid = c.tid;
-- 多张表隐式内连接写法
/*
-- 伪代码
select *
from A a,
B a,
C c
where a.id = b.id
and b.id = c.id;
*/
-- 显式内连接
select *
from teacher t
inner join course c on t.tid = c.tid;
-- inner可省略
select *
from teacher t
join course c on t.tid = c.tid;
-- 多张表显式内连接写法
/*
-- 伪代码
select *
from A a
join B b on a.id = b.id
join C c on b.id = c.id;
*/
-- 2、外连接
/*
1) 外连接是以某一张表为主,不是求交集
2) 外连接分为三种
左外连接:以左表为主,会把左表的数据全部输出,右表有交集的数据输出,没有交集的数据则输出NULL
右外连接:以右表为主,会把右表的数据全部输出,左表有交集的数据输出,没有交集的数据则输出NULL
满外连接:显示左表和右表的全部数据(并集)
*/
-- 给左表添加一行右表没有的数据
insert into teacher
values ('06', '周七');
-- 左外连接
select *
from teacher t
left outer join course c on t.tid = c.tid;
-- outer可省略
select *
from teacher t
left join course c on t.tid = c.tid;
-- 左外连接多表查询
/**
-- 伪代码
select *
from A a
left join B b on a.id = b.id
left join C c on b.id = c.id;
*/
-- 右外连接
-- 给右表添加一行左表没有的数据
insert into course
values ('04', '地理', '05');
select *
from teacher t
right outer join course c on t.tid = c.tid;
-- outer可省略
select *
from teacher t
right join course c on t.tid = c.tid;
-- 满外连接(左外和右外的并集)
select *
from teacher t
full join course c on t.tid = c.tid;
网友评论