对inner join、left join、right join和full join的学习是在大学时候,近来公司常使用它们,对它们的认识随着时间的逝去已渐趋渐远,借此机会重新温习一下:
table1 table2
id1 class_name id2 name
01 一年级 01 张三
02 二年级 02 李四
03 三年级 04 王五
1、able1 left join table2 其连接的记录数与table1表的记录数相等,此时等价于table2 right join table1,例如 select t1.* ,t2.* from table1 t1 left join table2 t2 on id1= id2 结果是:
id1 class_name id2name
01 一年级 01 张三
02 二年级 02 李四
03 三年级NULL NULL
2、able1 right join table2 其连接的记录数与table2表的记录数相等,此时等价于table2 left join table1,例如select t1.*,t2.*from table1 t1right join table2 t2 on id1 = id2 结果是:
id1 class_name id2 name
01 一年级 01 张三
02 二年级 02 李四
NULLNULL 04 王五
3、table1 inner join table2 其连接的记录数是table1和table2表on条件都有的记录数,即两表都有的数据,例如 select t1.* ,t2.* from table1 t1 inner join table2 t2 on t1 = t2 结果是:
id1 class_name id2 name
01 一年级 01 张三
02 二年级 02 李四
4、table1 full join table2 其连接的记录数是两表所有的总共的数据,例如 select t1.* , t2.* from table1 t1 full join table2 t2 结果是:
id1 class_nameid2 name
01 一年级01 张三
02 二年级02 李四
03 三年级NULL NULL
NULL NULL 04 王五