day35 MySQL多表查询

原文链接: https://blog.csdn.net/fightingXia/article/details/82813123

##概述
本篇blog主要讲解多表查询,包括连接查询和子查询,连接又分为交叉连接,内连接,外连接,外连接又分为左外连接和右外连接。

本篇blog主要以student表和score表为例说明多表查询的操作。

create table student (
    id int(11) primary key auto_increment,
    name varchar(100) default '',
    age int(11) default 0
);
 

score表结构如下:

create table student (
    id int(11) primary key auto_increment,
    student_id int(11),
    type varchar(100) default '',
    score int(11) default 0
);
 

 
##交叉查询

交叉查询使用cross join关键词。使用示例如下:

select * from student cross join score
 

说明:此时得到的数据共12行,7列。这是一种笛卡尔积运算,即行数为两表行数相乘,列说为之前两列相加。

这种用户显然没有丝毫意思,但我们添加where条件后,就变得有意义了,如下:

select * from student st cross join score sc where st.id = sc.student_id
结果如下:

此时可以清晰的看到每个学生的各个成绩。

在开发中最常用的是下面语句:

select st.name,st.age,sc.type,sc.score from student st,score sc where st.id = sc.student_id
说明:

此时分别给student和score分别起了别名st和sc。
此时cross join关键词可以省略,使用逗号隔开即可。
此时查询我们需要的字段即可。
##内连接查询
内连接使用关键词inner join。sql示例如下:

select * from student st inner join score sc on st.id = sc.student_id
 

注:这种方式与交叉连接得到的结果相同。所以这种方式很少使用。

##外连接查询
外连接分为左外连接和右外连接。

##左外连接(以左边的表为主表)
左外连接使用关键词:left outer join。示例如下:

select * from student st left outer join score sc on st.id = sc.student_id
 

说明:左外连接会获取左边的所有数据。

##右外连接(以右边的表为主表)
左外连接使用关键词:right outer join。示例如下

select * from student st right outer join score sc on st.id = sc.student_id
 

说明:右外连接会获取右边的所有数据。

##嵌套查询
嵌套查询也叫子查询,示例如下:

select * from score where student_id in (select id from student where name='guoxiang')
得到的结果如下:

说明:此时先根据name从student表中获取id,然后根据student_id获取score表中的数据。
 

猜你喜欢

转载自blog.csdn.net/gaosong0623/article/details/102408820