MySQL基础-连接查询

2020-12-11  本文已影响0人  小飞船1号

一、等值连接 .....=......

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 

二、内连接 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
#查询所有学生的成绩,包括没有成绩的学生,需要显示课程名
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
#查询所有课程的成绩,包括没有成绩的课程,需要显示学生信息
img_rightjoin.gif

使用左右连接(题目中包含所有,没有字眼需要用到左右连接)

五、自关联

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
上一篇 下一篇

猜你喜欢

热点阅读