tip:聚合函数只能用在select或者having条件之后。
用limit取代子查询
适用于查询最大,最小值的情况。比如
查询Score表中的最高分的学生学号和课程号。
可以先查出最高分的的分值然后再条件查询
select
sno,
cno
from score
where degree = (select max(degree)
from score);
用limit取代之后:
select
sno,
cno
from score
order by degree
limit 0, 1;
免去了子查询,性能更高,更简洁。
多表查询技巧
要想进行多表查询,先生成表关系。
然后看条件
比如:#查询“张旭“教师任课的学生成绩。
要查询的是 成绩 那我们就
select degree
通过谁查成绩呢,通过 教师 查成绩,从表关系可以看出,从教师到成绩需要经过3张表。那我们就
from score s, course c, teacher t
既然 合并表,就要去笛卡儿积
where s.cno = c.cno and t.tno = c.tno
最后加上条件 教师的名称为“张旭”
and tname='张旭'
最后合并的语句就是
select degree
from score s, course c, teacher t
where s.cno = c.cno and t.tno = c.tno and tname='张旭'
查询完毕。
简单SQL多表查询基本都是这个套路。