一、等值连接 .....=......
select * from 表1 as b1,表2 as b2 where b1.字段=b2.字段
再有其他条件,直接加在后边即可
select * from stu,course,score
where stu.stuid=score.stuid and course.cid=score.cid
- 必须要出现后边的等值条件,按照=的两边,取交集
- 不会出现新表,只是一个显示结果
- 先连接成一个笛卡尔积(生成记录总数=表1的总数*表2的总数),在根据条件筛选
- 会产生临时表,占内存
二、内连接 inner join.....on.......
select * from 表1
inner join 表2 on 表1.字段=表2.字段
where 条件
order by .....
limit ....
select * from stu
inner join score on where stu.stuid=score.stuid
inner join course on course.cid=score.cid
where stu.name='王昭君'
#先两个表连接,在和第三个表连接
#*要写成列名时,列名要加前缀表明是哪个表的,有重复的
#起别名,只能用别名
- 先根据条件筛选,在连接两个表
- 不会产生临时表,不占内存,性能高一些
img_innerjoin.gif
三、左连接 left join.....on.....
select * from 表1
left join 表2 on 表1.字段=表2.字段
select * from stu
left join score on where stu.stuid=score.stuid
#join前边生成的结果作为左表
left join course on course.cid=score.cid
#查询所有学生的成绩,包括没有成绩的学生,需要显示课程名
- join前面生成的结果作为左边,join后面的是右表,把左表的数据全部显示
- 取左表所有结果,右表有符合的连接到一起成一条数据,没有符合的右表部分字段就都填上null成一条数据
- 和内连接的区别就是,内连接没找到符合的不会显示null,该条不会存在表中,所以只要有右表不符合的情况,左表结果不会全部显示
img_leftjoin.gif
四、右连接 right join....on.....
select * from 表1
right join 表2 on 表1.字段=表2.字段
select * from score
right join course on where course.cid=score.cid
left join stu on stu.stuid=score.stuid
#查询所有课程的成绩,包括没有成绩的课程,需要显示学生信息
- join前面生成的结果作为左边,join后面的是右表,把右表的数据全部显示
- 取右表所有结果,左表有符合的连接到一起成一条数据,没有符合的左表部分字段就都填上null成一条数据
img_rightjoin.gif
使用左右连接(题目中包含所有,没有字眼需要用到左右连接)
- 只要明白那个是左表、右表;
- 那个需要所有结果;
- 那个需要null值;
五、自关联
-
一个表关联多次
select * from areas as sheng,areas as shi
where sheng.aid=shi.pid
select * from areas as sheng,areas as shi,areas as qu
where sheng.aid=shi.pid and shi.aid=qu.pid
- 数据之间有上下级关系
- 在一个表中存储所有数据
- 从一个表中查询多次,必须起别名