admin

[Oracle]复习笔记-SQL部分内容

admin 运维技术 2023-02-27 802浏览 0

 

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
--日期型数据也能实现取整,执行时舍去时分秒,不会进位。

[Oracle]复习笔记-SQL部分内容

(2)关于空值 null

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

 

 

继续浏览有关 数据库技术文章/教程 的文章
发表评论