CMU15445笔记-Relational Data Model&SQL

473 阅读2分钟

DBMS(数据库系统)

Abstraction

其抽象: 用统一的数据结构存储数据; 通过高级语言操作数据; 逻辑层和物理层分析, user只关心逻辑层, DBMS开发者才关心物理层的东西

数据模型

即对需要存储的数据进行建模, 常见的数据模型:

  • Relational: 大部分属于此
  • Key/Value
  • Graph
  • Document
  • Column-family
  • Array/Matrix

关系模型

Relation & Tuple

每个关系都是一个无序集合, 其中的元素称为tuple, 由一组属性构成, 属性在路基上有内在联系

Primary Keys

在一个Relation里唯一确定一个tuple

Foreign Keys

唯一确定另一个relation中的一个tuple

Data manipulation Languages(DML)

查询数据有两种方式

  • Procedural(程序性的), 指定具体查询策略
  • Non-Procedural, 只指定想要查询哪些数据, 不关心具体是怎么做的, 比如SQL

关系代数

关系代数是一种Relational Model的具体实现方式

image-20211129202231430

Advanced SQL

  • Aggregations + Group By
  • String / Date / Time Operations
  • Output Control + Redirection
  • Nested Queries
  • Common Table Expression
  • Window Functions

示例:(enrolled -> 注册的, 招收)

image-20211129203039127

Aggregates

Functions that return a single value from a bag of tuples

有AVG(平均值), MIN, MAX, SUM(求和), COUNT(计数)

这种函数一般只用于select

select COUNT(login) as cnt from student where login like '%@cs'
select AVG(gpa), COUNT(sid) from student where login like '%@cs'

DISTINCT Aggregate

COUNT, SUM和AVG支持DISTINCT关键字

select COUNT(DISTINCT login) from student where login like '%@cs'

image-20211129204125220

意义不明的ppt

GROUP BY

把tuple分成不同的自己, 并且对这些子集进行整合计算

select AVG(s.gpa), e.cid
from enrolled as e, student as s
where e.sid = s.sid
group by e.cid

image-20211129204427530

规则

Non-aggregated values in SELECT output必须在GROUP BY里出现

HAVING

group by配合使用

Filters results based on aggregation computation

select AVG(s.gpa) as avg_gpa, e.cid
from enrolled as e, student as s
where e.sid = s.sid
group by e.cid
having AVG(s.gpa) > 3.9

image-20211129204925519

String Operations

不同的db对于大小写之类有不同的规定, 也有不同的函数...

  • like: 字符串匹配, 其中%匹配任意子字符串(包括空串), _匹配任意一个字符
select * from enrolled as e where e.cid like '15-%'

Date/Time Operations

不同DBMS中的定义和用法不一样