sql多表连接查询 连接查询 join查询

join连接

先来看两张表的结构,方便你了解下文的操作语句。

内连接

select column_1, column2 from tableA inner join tableB on tableA.id = tableB.id;
# 只显示匹配数据,显示A表中和B表中有匹配的数据
select name, title from poets inner join poetries on poets.id = poetries.id;

外连接

左外连接

显示A表中的所有数据,如果在b表中没有与之匹配的值用null填充

# 找出A表中和B表相同的Id进行等值连接
select column_1, column2 from tableA left join tableB on tableA.id = tableB.id;
# 显示poets表中所有记录,如果poets中的记录在poetries表中的没有匹配的值,那么用null填充。
select name, title from poets left join poetries on poets.id = poetries.id;
右外连接
# 显示B表中所有与之匹配所有记录,B表中如果在A表中没有匹配,用null值填充。
select column_1, column2 from tableA right join tableB on tableA.id = tableB.id;
select name, title form poets right join poetries on poets.id = poetries.id;

全连接

select column_1, column_2 from tableA full join tableB on tableA.id = tableB.id;
select name, title from poets full join poetries on poets.id = poetries.poet_id;

交叉连接

# cross join 做笛卡尔, 将A表中的所有字段和B表中的所有字段进行交叉连接,A表中的每一条记录都与B表中的所有记录进行匹配。
select column_1, column_2 from tableA corss join tableB;

附加条件的连接

 select name, title from poets inner join poetries on poets.id = poetries.poet_id where poets.id <5 ;
 select name, title from poets inner join poetries on poets.id = poetries.poet_id where poets.id <5 order by poetries.id;

猜你喜欢

转载自www.cnblogs.com/ghostdot/p/12543002.html