记录一个踩过的坑 表连接查询相关

create table tbl_a(id integer,id2 integer);
create table tbl_b(id integer,id2 integer);
truncate tbl_a;
truncate tbl_b;
insert into tbl_a values (1,1),(2,2),(3,3),(4,4),(5,5),(6,6);
insert into tbl_b values (1,1),(2,2),(3,3),(4,4),(7,7),(8,8);

select * from tbl_a inner join tbl_b using (id) where tbl_b.id2 = 3;
-- 3,3,3
select * from tbl_a inner join (select * from tbl_b where id2 = 3) t2 using (id);
-- 3,3,3

select * from tbl_a left join tbl_b using (id) where tbl_b.id2 = 3;
-- 3,3,3
select * from tbl_a left join (select * from tbl_b where id2 = 3) t2 using (id);
-- 1,1,null
-- 2,2,null
-- 3,3,3
-- 4,4,null
-- 5,5,null
-- 6,6,null

select * from tbl_a right join tbl_b using (id) where tbl_b.id2 = 3;
-- 3,3,3
select * from tbl_a right join (select * from tbl_b where id2 = 3) t2 using (id);
-- 3,3,3

因为正常用inner join 比较多,容易产生错觉,认为条件放里面和放外面是一样的。

FROM T1 CROSS JOIN T2 INNER JOIN T3 ON conditionFROM T1,T2 INNER JOIN T3 ON condition并不完全相同,因为第一种情况中的condition可以引用T1,但在第二种情况中却不行。

猜你喜欢

转载自blog.csdn.net/weixin_42767321/article/details/86607592