自关联查询和子查询

自关联查询:

id,area,parentAreaId

1,广东省,0

2,广州市,1

3,梅州市,1

4,白云区,2

5,天河区,2

广东省,广州市,天河区

找出广东省里的所有市:select * from region where name = "广东省"

1.将2张表关联(同一张表):select * from region as r1 inner join region as r2 on r1.id = r2.pid where r1.name = "广东省"

注意:上下级关系包含,公司的层级关系,游戏里帮派层级关系

子查询:

查找年龄小于20岁的学生

select studentname from student where studentage < 20 ;

查找姓名为小明的学生成绩

select * from score inner join student on score.stuid = student.id where student.studentname = "小明";

查找年龄小于20岁的学生姓名的成绩(因为学生可能有多个,所以使用in)

select * from score inner join student on score.stuid = student.id where student.studentname in (select studentname from student where studentage < 20 );

即为子查询,查询里面有查询;

存在某个条件下,才做某个查询(exists)

如果有学生大于50岁才将老师查找出来;exists条件查找,存在exists后面的查询内容,才执行前面的查找

select * from teacher where exists (select studentname from student where studentage > 50 );

尽量不要让数据库做太多操作,会降低性能,而且嵌套越多,越难让别人看懂

猜你喜欢

转载自blog.csdn.net/small_rain_/article/details/112555037