设有表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。
表名长的时候最好使用短的别名。