前言
sql语句一直是我的弱项,我总觉得它不像编程语言那样具有逻辑性,事实的确如此,下定决心攻克它。文章若有错误,请及时联系我更正,免得误人子弟。小伙伴请记住,sql语句的语法顺序和执行顺序并不一致。
尽量使用表连接,如下图所示,没有使用表连接时,输出表会有a(列)+b(列)个字段,a(条)*b(条)个数据,而使用表连接会减少很多.
1
|
FROM
a,
b
|
还有更多的一些需要注意事项,感兴趣小伙伴请自行百度查询,这里只是解释我对一些sql的理解
语法顺序
select
from
where
group by
having
union
order by
执行顺序
from
where
group by
having
select
union
order by
sql示例
表
/*student(学号#,姓名,性别,年龄)
course(课程号#,课程名,教师号#)
score(学号#,课程号#,成绩)
teacher(教师号#,教师名)*/
--1.查询“001”课程比“002”课程成绩高的所有学生的学号
写这个sql之前,你要好好体会sql语言的核心是对表的引用这句话
1、from score a,score b--先查出笛卡尔乘积临时表(设计到比较肯定要用多表查询)
2、where a.cNo='c001' and b.cNo='c002' and a.stuNo=b.stuNo and a.score>b.score --限制条件
3、select a.stuNo--查出学号
整体sql
select a.stuNo from score a,score b where a.cNo='c001' and b.cNo='c002' and a.stuNo=b.stuNo and a.score>b.score
--2.查询平均成绩大于60分的同学的学号和平均成绩
having语句弥补where语句不能与聚合函数联合使用的缺陷
人分三六九等,oralce用group by来处理等级.
select stuNo,avg(score)from score
group by stuNo
having avg(score)>60
--3.查询所有同学的学号、姓名、选课数、总成绩
一旦涉及到多表查询,脑海里要联想到笛卡尔乘积这个图,博客链接,另外 查询到数量等基本上要分组 然后在select后面用一些函数 如sum count等
http://www.360doc.com/content/14/1229/21/7635_436727229.shtml
from student a,score b
where a.stuNo=b.stuNo --表关联
group by a.stuNo,a.stuName
select a.stuNo,a.stuName,count(cNo),sum(score)
总体
select a.stuNo,a.stuName,count(cNo),sum(score) from student a,score b where a.stuNo=b.stuNo group by a.stuNo,a.stuName
--4.查询姓“赵”的老师的个数
where tName like '赵%'
group by tName
--5.查询没学过“某某”老师课的同学的学号、姓名
1、确定直接表,学号姓名=>student,“某某”老师课指代教师名teacher
2、确定间接表,分析表之间关系,找过渡表,student和teacher之间没有直接关系
2.1)student和score有学号对应关系,score和course有课程号对应关系
2.2)course和teacher有教师号对应关系
2.3)student->score->course->teacher
3、好像有那么一点关系
4、select stuNo stuName from student where stuNo not in(select a.stuNo from student a,score b where a.stuNo= b.stuNo and cNo in (select d.cNo from teacher c,course d where c.tNo = d.tNo and c.tName='钱市保'))
-6.查询学过“001”并且也学过编号“002”课程的同学的学号、姓名;
突然感觉很简单,下面是我第一次写出的sql,发现大错特错,学过并且也学过,没理解透彻。
错误答案:select a.stuNo,a.stuName from student a,score b where b.cNo in ("001","002");
正确答案:
select a.stuNo,a.stuName from student a,score b,score c
where a.stuNo=b.stuNo and b.stuNo=c.stuNo and b.cNo='c001' and c.cNo='c002'