SQL的相关笔记

Sql的通用语法

 

SQL的分类

 

 

 

3. JOIN的用法

内连接INNER JOIN是最常用的连接操作。从数学的角度讲就是求两个表的交集,从笛卡尔积的角度讲就是从笛卡尔积中挑出ON子句条件成立的记录。有INNER JOIN,WHERE(等值连接),

左连接:LEFT JOIN

 

左连接可以看做在内连接的基础上,把左表中不满足ON条件的数据也显示出来,但结果中的右表部分中的数据为NULL

右连接:RIGHTJOIN

 

以右表为基础,获取匹配关系的记录,如果左表中没有匹配项,NULL表示

内连接:INNER JOIN

内连接需要用ON来指定两张表需要比较的字段,最终结果只显示满足条件的数据

 

1.group by的用法,一般而言,出现每个,分别等字眼,或者可以加进去这些字眼时会用到分组,如这一个题目就是每个同学,另外注意group by 后对组进行过滤用having 而不是where,ps:先执行where,再执行group by

2.在去重时一般考虑用distinct,但是group by 其实也可以达到去重效果,就效率来讲,当表格大时,后者会更快,因为考虑的数据条数是组数,而distinct是要考虑全部数据)

排序查询 order by

语法:order by 子句

order by 排序字段1 排序方式1 , 排序字段2 排序方式2...

注意: 如果有多个排序条件,则当前边的条件值一样时,才会判断第二条件。

-- 例子
SELECT * FROM person ORDER BY math; --默认升序
SELECT * FROM person ORDER BY math desc; --降序

1 查询" 01 “课程比” 02 “课程成绩高的学生的信息及课程分数

select student.* from ,score01,score02

from student,

(select t1.sid,score01,score02 ) from (select sid,socre from sc where cid='01') t1,

(select sid,socre from sc where cid='01') t2 where t1.sid=t2.sid and score01>score02)r

where student.sid=r.sid

1.1 查询同时存在" 01 "课程和" 02 "课程的情况

select student.*,score01,score02

from student ,

(select t1.sid,score01,score02

from (select sid,score score01 from sc where cid='01') t1,

(select sid,score score02 from sc where cid='02') t2

where t1.sid=t2.sid

)r

where student,sid = r.sid

1.2 查询存在" 01 "课程但可能不存在" 02 "课程的情况(不存在时显示为 null ) select student.*,score01,score02 from student, (select t1.sid,score01,score02 from(select sid,score score01 from sc where cid='01')t1 left join (select sid,score score02 from sc where cid='02')t2 on t1.sid=t2.sid )r where student.sid = r.sid;

-- 1.3 查询不存在" 01 "课程但存在" 02 "课程的情况

select student.*,score01,score02 from student, (select t2.sid,score01,score02 from(select sid,score score01 from sc where cid='02')t2 left join (select sid,score score02 from sc where cid='01')t1 on t1.sid=t2.sid where t1.sid is null )r where student.sid = r.sid;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值