30秒懂SQL中的join
注:本文仅仅是本人在网上看到的比较好的文章,为了以后复习方便,就文章 完全复制下来。原文地址如下:http://www.habadog.com/
预先生成两张测试表,并插入一下测试数据:
create table t1(id int, name char(10), primary key (id));
create table t2(id int, score int, primary key (id));
insert into t1 values(1, “lucy”);
insert into t1 values(2, “lily”);
insert into t1 values(3, “jack”);
insert into t2 values(2, 20);
insert into t2 values(3, 30);
insert into t2 values(4, 40);
t1表内容如下:
t2表内容如下:
下面来简述join和left join/right join的区别:
inner join
select * from t1 inner join t2 on t1.id = t2.id;
公共部分的数据才会被查询出来;
left join
select * from t1 left join t2 on t1.id = t2.id;
查询出来的结果和前表记录数一样多;
right join
select * from t1 right join t2 on t1.id = t2.id;
能转化为
select * from t2 left join t1 on t1.id = t2.id;
时间: 2024-10-25 19:33:25