多表连接查询
SQL多表连接查询
外连接:左连接,右连接,完全外连接
select * from student left join course on student.ID=course.ID
如果左表中某行在右表没有匹配,则结果中对应右表的部分全部为空(NULL)。
如果两个表为一对一的关系,结果的行数为左表行数
select * from student right join course on student.ID=course.ID
如果左表中某行在右表没有匹配,则结果中对应左表的部分全部为空(NULL)。
如果两个表为一对一的关系,结果的行数为右表行数
select * from student full join course on student.ID=course.ID
如果右表中某行在左表中没有匹配,则结果中对应行右表的部分全部为空(NULL),如果左表中某行在右表中没有匹配,则结果中对应行左表的部分全部为空(NULL)。
内连接
select * from student inner join course on student.ID=course.ID
inner join 是比较运算符,只返回符合条件的行。不返回id为空的行
交叉连接
select * from student cross join course
没有 WHERE 子句的交叉联接将产生连接所涉及的表的笛卡尔积。第一个表的行数乘以第二个表的行数等于笛卡尔积结果集的大小。
如果加上WHERE子句,则结果和内连接相同
当两表为多对多关系的时候,我们需要建立一个中间表student_course,中间表至少要有两表的主键,当然还可以有别的内容。
select s.Name,C.Cname from student_course as sc left join student as s on s.Sno=sc.Sno left join course as c on c.Cno=sc.Cno
对表student_course使用两次左连接,用在student和course两个表上
多表查询
最新推荐文章于 2024-11-03 22:59:42 发布