设有表tb1和tb2
1、直接计算完整的笛卡尔积
select * from tb1 join tb2;
默认为内连接,相当于select * from tb1 inner join tb2;
2、内连接 加on条件,理解为在笛卡尔积中取出满足条件的记录
select a1.ziduan1, a2.ziduan2 from tb1 a1 inner join tb2 a2 on a1.id = a2.a1_id;
3、左连接 左侧表在右侧表没有满足条件的记录时,保留左侧表记录的字段数据,右侧表字段的数据设置为null。
select * from tb1 a1 a1left join tb2 a2 on a1.id = a2.a1_id;
4、右连接 右侧表在左侧表没有满足条件的记录时,保留右侧表记录的字段数据,左侧表字段的数据设置为null。
select * from tb1 a1 right join tb2 a2 on a1.id = a2.a1_id;
5、
select * from tb1 a1 left join tb2 a2 on a1.id = a2.a1_id where a2.a1_id is null;
6、
select * from tb1 right join tb2 on a1.id = a2.a1_id where a1.id is null;
7、
select * from tb1 left join tb2 on a1.id = a2.a1_id where a2.a1_id is null union select * from tb1 right join tb2 on a1.id = a2.a1_id where a1.id is null;
需要注意null的特殊性,null不等于null,要用is判断值是不是null。
表名长的时候最好使用短的别名。
本文详细介绍了SQL中的五种连接类型:笛卡尔积、内连接、左连接、右连接及全外连接。通过具体的SQL语句示例,展示了如何在实际操作中应用这些连接方式,并特别强调了处理NULL值的方法。

1424

被折叠的 条评论
为什么被折叠?



