1、准备两个表:Student,Course,其中student.C_S_Id=Course.C_Id(即Student 表中的 C_S_Id 字段为外键列,关联的是 Course 表的 C_Id 主键列)
2、内连接(table1 inner join table2 on 条件表达式):满足on条件表达式,内连接是取满足条件表达式的两个表的交集(其中inner可以省略);
select * from Student s
inner join Course c on s.C_S_Id=c.C_Id
结果如下:
3、外连接(outer join)分为:左外连接(left outer join / left join),右外连接(right join / right outer join)和全外连接(full join / full outer join)
(1)左外连接(table1 left join table2 on 条件表达式):满足on条件表达式,左外连接是以左表为准,返回左表所有的数据,与右表匹配的则有值,
没有匹配的则以空(null)代替。
select * from Student s
left join Course c on s.C_S_Id=c.C_Id
结果如下:
(2)右外连接(table1 right join table2 on 条件表达式):满足on条件表达式,右外连接是以右表为准,返回右表所有的数据,与左表匹配的则有值,
没有匹配的则以空(null)代替。
select * from Student s
right join Course c on s.C_S_Id=c.C_Id
结果如下:
(3)全外连接(table1 full join table2 on 条件表达式):满足on条件表达式,返回两个表符合条件的所有行,a表没有匹配的则a表的列返回null,
b表没有匹配的则b表的列返回null(即返回的是左外连接和右外连接的并集)。
select * from Student s
full join Course c on s.C_S_Id=c.C_Id
结果如下:
4、交叉连接(table1 cross join table2):交叉连接将返回被连接的两个表的笛卡尔乘积,返回结果的行数等于两个表的行数的乘积。
不加条件的交叉连接SQL语句:
select * from Student s
cross join Course c
加上条件返回满足条件表达式的两个表的行(交叉连接加条件只能用where):
select * from Student s
cross join Course c
where s.C_S_Id=c.C_Id;
结果如下:
5、自连接:表与表自己连接此时需要给表取别名,而且后面加条件时也只能用where,这点同全外连接一样。
select s1.S_Name,s2.S_age
from Student s1,Student s2
where s1.S_BirthDate=s2.S_BirthDate
原文:https://www.cnblogs.com/hdc520/p/11101849.html