表连接查询
- 示例表:
select * from tParent
select * from tChild
- 内连接(join 或者inner join ): 只有两个表相匹配的行才能在结果集中出现
select * from tParent p inner join tChild c on c.cPId=p.pId
select * from tParent p join tChild c on c.cPId=p.pId -- 效果同上
select * from tParent p,tChild c where c.cPId=p.pId -- 效果同上(如果不加where c.cPId=p.pId,返回笛卡尔积)
- 外连接
- 左外连接(left join 或left outer join)匹配所有符合条件左边的数据(注:右表未匹配行的全部列为NULL)
select * from tParent p left join tChild c on c.cPId=p.pId
select * from tParent p left outer join tChild c on c.cPId=p.pId -- 效果同上
-
- 右外连接(right join 或者 right outer join)匹配所有符合条件右的数据(注:左表未匹配行的全部列为NULL)
select * from tParent p right join tChild c on c.cPId=p.pId
select * from tParent p right outer join tChild c on c.cPId=p.pId -- 效果同上
-
- 全外连接(full join 或者 full outer join)两表合并,匹配的行合并成一行,未匹配的行的所有列为NULL
select * from tParent p full join tChild c on c.cPId=p.pId
select * from tParent p full outer join tChild c on c.cPId=p.pId -- 效果同上
- 交叉连接(cross join)
* 不带where条件,返回笛卡尔积(两表行的乘积)的结果集
select * from tParent p cross join tChild c
* 带where条件,返回符合where条件的结果集
select * from tParent p cross join tChild c where c.cPId is NULL -- 返回笛卡尔积且符合where条件的结果集
select * from tParent p cross join tChild c where c.cPId=p.pId -- 条件中有关联,等同于inner join
- 联合查询。union(去除重复行)、union all(连接表的所有行都保留,不去除重复行)
/* [此段为网摘]
union是一个特殊的运算符,用于将两个或两个以上的查询产生一个结果集。join将信息水平连接(添加更多列),而union将信息垂直连接(添加更多行)。
当使用union处理查询时,要注意以下几个关键点:
(1)、所有union的查询必须在select列表中有相同的列数。即如果第一个查询有3个列数,第二个查询也要只有3个列数。
(2)、union返回结果的标题集仅从第一个查询中获得,无论第二个查询如何命名或取别名都不会更改。
(3)、查询中对应的列的数据类型必须隐式一致。注意不要求完全一致,只需要隐式一致。
(4)、与其他非union不同,union的默认返回选项为distinct,而不是all。union all语句与union的不同点仅仅在于遇到相同的记录,全部保留而已。
*/
-- union 默认使用了distinct(过滤重复行)
select pName Name from tParent
union
select cName from tChild
-- union all 所有行(不过滤重复行)
select pName Name from tParent
union all
select cName from tChild
表连接 on与where比较 关联条件链接 + 数据过滤条件
- inner join
- 未加条件(匹配所有符合条件的数据)
select * from tParent p inner join tChild c on c.cPId=p.pId
-
- 条件加在on上(匹配所有符合条件的数据)
select * from tParent p inner join tChild c on c.cPId=p.pId and c.cState=0
-
- 条件加在where上(匹配所有符合条件的数据)
select * from tParent p inner join tChild c on c.cPId=p.pId where c.cState=0
- left join
- 未加条件(左表所有匹配,没匹配的右表行的所有列为NULL)
select * from tParent p left join tChild c on c.cPId=p.pId
-
- 条件加在on上(先on条件匹配及过滤左右表,然后再产生结果集。匹配左表所有行,右表不符合条件行的所有列为NULL)[结果集中包含左表的所有行]
select * from tParent p left join tChild c on c.cPId=p.pId and c.cState=0
-
- 条件加在where上(先匹配左表所有行,where再对结果集进行过滤)[结果集中可能不包含左表的所有行]
select * from tParent p left join tChild c on c.cPId=p.pId where c.cState=0
- right join
- 未加条件(右表所有行,左表没匹配的行的所有列显示NULL)
select * from tParent p right join tChild c on c.cPId=p.pId
-
- 条件加在on上(先on条件匹配及过滤左右表,然后再产生结果集。匹配右表所有行,左表不符合条件行的所有列为NULL)[结果集中包含右表的所有行]
select * from tParent p right join tChild c on c.cPId=p.pId and c.cState=0
-
- 条件加在where上(先匹配右表所有行,where再对结果集进行过滤)[结果集中可能不包含右表的所有行]
select * from tParent p right join tChild c on c.cPId=p.pId where c.cState=0