内连接【inner join 或者 join】
外连接
左连接 left join 或者 left outer join
右连接 right join 或 righ outer join
完全外连接 full join 或者 full outer join
没有 创建 外键 !!!
create databases testJoin;
-- 1、person表
create table person(
id int,
name varchar(20),
cardId int
);
-- 2、card表
create table card(
id int,
name varchar(20)
);
insert into card values(1, '饭卡');
insert into card values(2, '建行卡');
insert into card values(3, '农行卡');
insert into card values(4, '工商卡');
insert into card values(5, '邮政卡');
select * from card;
insert into person values(1, '霸刀宋壹', 1);
insert into person values(2, '暴走丁二', 3);
insert into person values(3, '忍者张三', 6);
select * from person;
3.1、内连接【inner join查询、join查询】
内联查询,其实就是两张表中的数据,通过某个字段相等,查询出相关记录数据。
select * from person inner join card on person.cardId = card.id;
select * from person join card on person.cardId = card.id;
3.2、左外连接【left join、left outer join】
左外连接,会把左边表里面的所有数据取出来,而右边表中的数据,如果有相等的,就显示出来;
如果没有,就会补NULL。
select * from person left join card on person.cardId = card.id;
select * from person left outer join card on person.cardId = card.id;
3.3、右外连接【right join、right outer join】
右外连接,会把右边表里面的所有数据取出来,而左边表中的数据,如果有相等的,就显示出来;
如果没有,就会补NULL。
select * from person right join card on person.cardId = card.id;
select * from person right outer join card on person.cardId = card.id;
3.4、全外连接【full join】
select * from person full join card on person.cardId = card.id;
select * from person right join card on person.cardId = card.id
union
select * from person left join card on person.cardId = card.id;
连接的好处:不用创建外键;可以根据连接表的某字段相等,求 交集、并集。
1、内连接【两个表的交集】
2、左外连接
3、右外连接
4、全外连接
select * from person full join card on person.cardId = card.id;
select * from person right join card on person.cardId = card.id
union
select * from person left join card on person.cardId = card.id;