drop table if exists test1;
create table test1(
id INT(10),
name VARCHAR(10),
class varchar(10)
);
drop table if exists test2;
create table test2(
id INT(10),
name VARCHAR(10),
class VARCHAR(10)
);
insert into test1 values(1,'zhang','xx');
insert into test1 values(2,'xc','dd');
insert into test1 values(3,'dsf','ww');
insert into test2 values(2,'sd','ggg');
insert into test2 values(3,'45','fe');
insert into test2 values(4,'df','vvv');
建立表:
内连接:inner join on,返回两个表的交集。
select * from test1 a,test2 b where a.id=b.id;
select * from test1 a inner join test2 b on a.id=b.id;
上面的两句语法返回的结果是相同。mysql自动给同名列的列名后面加上了1。
结果如图所示:
左连接:left join on,根据条件返回test1中存在的,因为test1的id是1,2,3,test2中id是2,3,4,所以结果集中只出现id为1,2,3的行,3在test2中不存在,所以test2中的内容显示为null。
select * from test1 a left join test2 b on a.id=b.id;
结果如图所示:
右连接:right join on,与左连接类似,返回test2中存在的。
select * from test1 a RIGHT join test2 b on a.id=b.id;
结果如图所示:
全连接:full outer join on,返回两个表的并集。(mysql不支持全连接,可以使用union产生相同效果)
select * from test1 a full outer join test2 b;
select * from test1 a left join test2 b on a.id=b.id union select * from test1 a right join test2 b on a.id=b.id;
结果如图: