1、内联查询
>inner join 或 join
2、外联查询
(1)左连接
>left outer join 或 left join
(2)右连接
>right outer join 或 right join
(3)完全外连接
>full outer join 或 full join
代码详解:
1、数据准备
(1)创建一个新的数据库
>create database testjoin;
(2)创建两个表person、card
>create table person(
-> id int ,
-> name varchar(20),
-> cardid int);
>create table card(
-> id int,
-> name varchar(20));
(3)添加数据
>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,'邮政卡');
>insert into person values (1,'张三',1);
>insert into person values (2,'李四',3);
>insert into person values(3,"王五",6);
2、查询
——上述两个表并没有创建外键
(1)inner join查询
>select * from person inner join card on person.cardid = card.id;
【注】内联查询,其实就是查询两张表中相等的数据(有关联的数据,上述是cardid对应card.id)
(2)left join (左外连接)
> select * from person left join card on person.cardid = card.id;
【注】左外连接就是将写在left join左侧的表的数据全部取出来而右侧的数据有的取出来如果没有补上NULL
(3)right join (右外连接)
>select * from card right join person on person.cardid = card.id;
【注】右外连接就是将写在right join右侧的表的数据全部取出来而左侧的数据有的取出来如果没有补上NULL
(4)full join(全外连接)
> select * from card full join person on person.cardid = card.id;
上述可知:mysql是不支持全连接的,可以通过将左连接与右连接用union加起来的方式:
>select * from card right join person on person.cardid = card.id union select * from card left join person on person.cardid = card.id;
【注】如上图:会将左边右边的表的数据全部显示出来,彼此之间没有的彼此间补NULL
关注个人公众号,有福利哦……