Relational databases: a key and a relationship
引入
4:42
数据库
学校图书馆将所有借阅记录保存在一个电子表格中。每一行包含学生姓名、班级、书名和日期。当学生更换班级时,数十行数据必须……
英文讲解 · 可切换中英文字幕
本课内容
| English | 释义 | 拼音 |
|---|---|---|
| relational database/rɪˈleɪʃənl ˈdeɪtəbeɪs/ | 关系数据库 | guān xì shù jù kù |
| primary key/ˈpraɪməri kiː/ | 主键 | zhǔ jiàn |
| foreign key/ˈfɒrən kiː/ | 外键 | wài jiàn |
| record/ˈrekɔːd/ | 记录 | jì lù |
| field/fiːld/ | 字段 | zì duàn |
| normalisation/ˌnɔːməlaɪˈzeɪʃn/ | 规范化 | guī fàn huà |
| inner join/ˈɪnə dʒɔɪn/ | 内连接 | nèi lián jiē |
| transaction/trænˈsækʃn/ | 事务 | shì wù |
什么能解释这一观察结果?
- 在每个订单中重复使用用户地址,当地址变更时可能会产生冲突的记录。
What did Codd propose in 1970?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
The relational model.
构建模型
- 关系表包含行和属性。
- 主键用于标识一行;外键链接到另一张表中引用的键。
- 规范化可以减少不必要的重复和更新异常,同时保留有意义的关系。
- 主键:唯一标识表行的属性集。
- 外键:引用另一张表中键的属性集。
Which field is the best primary key for Students?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
It is unique and does not change.
选择可验证的证据
- 连接根据指定条件组合行。
- 结果数量取决于关系的基数和筛选器。
- 外键约束强制执行关系规则;它不会自动加密个人数据。
实验室任务: 设计一个不含真实个人信息的小型合成用户-订单数据集。声明键,测试重复插入和缺失引用插入,然后将查询结果与手工计算的预期表进行比对。
A foreign key holds the primary key of another table.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
It links the tables.
从已知量出发
- 已知:四位客户分别有2、0、3和1个订单。
- 从客户到订单的内连接返回2+0+3+1 = 6 行。
- 左连接还会保留没有订单的客户作为一行空值匹配行,因此此处为7。
你来试: 三个客户分别有 1、3 和 2 笔订单。客户-订单内连接会返回多少行?
一个客户可以产生多行匹配结果
每个客户的每笔匹配订单各产生一行;左连接还会为没有订单的客户保留一行NULL匹配结果。
What problem does normalisation prevent?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Store each fact once.
检查结论及其局限性
- 主键不必是人名。
- 连接操作并非简单的表拼接。
- 对于不可信输入,请使用参数化查询,而非通过原始字符串构建 SQL。
不正确: 外键不会自动对每一行进行加密。外键是表之间的引用链接——它确保被引用的行存在。它本身不提供加密功能;保护行内容属于独立的安全机制。
- 关系表包含行和属性。
- 连接根据指定条件组合行。
- 注意:主键不必是人名。
Four students have 0, 2, 2 and 3 enrolments. How many rows does an inner join of Students and Enrolments return?
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
0 + 2 + 2 + 3 = 7; the student with none is omitted.
Why is Ben missing from the join result?
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
An inner join returns only matches.
这是一张新卡片,翻译完成前会显示英文。
Integrity and transactions
- Referential integrity: an enrolment cannot refer to a StudentID that does not exist.
- A transaction 事务 is all-or-nothing (atomic): moving a student between classes must not leave them in both or neither.
An atomic transaction either completes fully or not at all.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
No half-moved records.
这是一张新卡片,翻译完成前会显示英文。
A name is not a key. Two students can share a name, and names change. Use a unique identifier that never changes as the primary key 主键.
这是一张新卡片,翻译完成前会显示英文。
A relational database 关系数据库 stores entities in tables of records and fields. A primary key identifies each record; a foreign key links tables; normalisation removes repetition; an inner join returns only matching rows; integrity rules and atomic transactions keep data consistent.
Design tables for a school library (books, members, loans) with primary and foreign keys, and write a query listing the titles borrowed by member 42.
Tables, keys, query.
出了什么问题?只有网站团队能看到这些信息。