联表查询join
联表查询分为Inner join、left join、right join
left join左连接:以左表为主。结果会将左表所有的查询信息列出,而右表只列出ON后条件与左表满足的部分。
right join左连接:以右表为主。结果会将右表所有的查询信息列出,而左表只列出ON后条件与右表满足的部分。
查询学生的学号,姓名和成绩从student学生表和result成绩表
Inner join:
select s.id,name,score
from student as s
inner join result as r
where s.id = r.id;
left join:
select s.id,name,score
from student as s
left join result as r
where s.id = r.id;
right join:
select s.id,name,score
from student as s
right join result as r
where s.id = r.id;
自连接
- 自连接是连接的一种用法,但并不是连接的一种类型,因为他的本质是把一张表当成两张表来使用。
- mysql有时在信息查询时需要进行对自身连接,所以我们需要为表来定义别名。
查询父子信息:把一张表看为两个一模一样的表,然后就可以对表进行其他操作了。
select a.categoryName as '父列',b.categoryName as '子列'
from category as a,category as b
where a.categoryid = b.pid;