Oracle笔记–SQL部分

整体框架

语句的执行顺序:
from →where →group by→having→select→order by

select *
from *
where *
group by *
having *
order by *

关于select

(1)当调用的不同表中存在相同名称的列时,需要指明表格

select student.name,class.name
from student,class

(2)重定义列名

select student.name as stuname --as可以省略

(3)当需要重定义的列名与sql保留关键字相同时需要使用双引号

select student.score as "value"

(4)使用distinct去重

select distinct(student.score) from student

关于from

(1)左右合并表格 a inter join b using(c),以列c为标准,合并表a和表b中列c值相同的行

-- 使用inter join,对于任意一个表格,若列c的值为空则该行数据不显示
from class inter join student using(stuname)
-- 若两个表格中关于同一项值的列名不同,使用“on + 判断”而不是“using()”
from class inter join student on class.stuname=student.name
-- 向左合并(当表a中列c为空时仍然显示表a的数据)left join
-- 向右合并 right join
-- 两个表中列c为空的行都显示 full join

(2)上下合并表格union(去重)与union all(不去重)
注意:union(all)要求两次select列数一定要相同,列必须拥有相似的数据类型

from (
   select student.age,student.name
from student
union all
select teacher.age,teacher.name
from teacher
) as allmessage -- 一般会起一个名字便于后续使用

关于where

 (1)查找某个值

where sid='BDT20040'

where sid like 'BDT20%' -- %代指零个或多个字符

(2)使用子查询

where SID in (
    select SID from class
    where class.name='Oracle')
-- not in这里就不写了,用法类似

where exists(
    select * from class    
    where class.name='Oracle' and class.sid=student.sid)
-- exists用于判断查询子句是否有记录,如果有记录返回 True,否则返回 False,与select后接的查找内容无关。not exists 同理

(3)判断是否为空

where sid is not null

 关于group by

当select中使用聚合函数时,非聚合函数项需要添加到group by中

常见的聚合函数有:avg()、count()、max()、min()

关于having

对于使用聚合函数的列,我们使用having的方法进行筛选

select class.name,max(score)
from class inter join student on class.stuname=student.name
group by class.name
having max(score)>80

关于order by

order by student.score
-- 默认为从小到大,可以设置为desc,改为从大到小

其他

(1)取整函数 round

select round(1.245,2) from dual
--四舍五入到两位小数,其中2可以省略,若省略则默认四舍五入到整数。dual表示空表。


select draw_time,trunc(draw_time) from usershi
--日期型数据也能实现取整,执行时舍去时分秒,不会进位。

(2)关于空值 null

  • 空值在判断值是否相等时(=、in)返回无法判断(不相等)
  • 但在使用group by时,空值会被视作同一项(相等)
  • count(字段/NULL) 不统计NULL值,count(null)=0

 


 

制作:BDT20040

如果还有想到啥的可以私聊我,我去补充一下(大概率咕咕咕就是了)

原文地址:http://www.cnblogs.com/liubaili/p/16817196.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性