跳到主要内容

A.3 · 数据库

IB 计算机科学 SL · 知识点 3

本主题的视频课程 打开视频页面
4:39

数据库

学校图书馆将所有借阅记录保存在一个电子表格中。每一行包含学生姓名、班级、书名和日期。当学生更换班级时,数十行数据必须……

英文讲解 · 可切换中英文字幕

3.1

范围与先修条件

English

This handout teaches Theme A3, Databases, for the course first assessed in 2027: relational databases, design and normalisation, and SQL.

Prerequisites: data types from B2 (integer, string, Boolean, real).

3.2

为什么要使用数据库?

English

One spreadsheet, many problems

A school library keeps loans in one spreadsheet: each row has the student's name, form, the book's title and author, and the date. When a student changes form, dozens of rows must be edited, and some are missed. Two rows now disagree about the same student. A database is designed to stop this.

Rows of small labelled drawers in a library card catalogue
A library card catalogue is a database on paper — records you can search and sort by index

Database fundamentals

A database 数据库 is an organised collection of data. A database management system 数据库管理系统 (DBMS) is the software that stores it, runs queries, controls access and makes backups.

Problem with flat files How a relational database helps
data redundancy 数据冗余: the same data stored many times each fact stored once
inconsistency 数据不一致: copies disagree one copy, so nothing to disagree
hard to search and combine SQL queries join tables
no control over who sees what user accounts and permissions

Tables, records and keys

A relational database 关系数据库 stores data in tables 表 (relations). Each record 记录 (row) is one item; each field 字段 (column, attribute) is one property.

Key Meaning Example
primary key 主键 a field whose value is unique for every record student_id
foreign key 外键 a field that holds the primary key of another table, linking them student_id in Loan
composite key 复合键 a primary key made of two or more fields (order_id, item_id)

Referential integrity 参照完整性 requires a non-null foreign key to match a referenced key (a primary or other suitable unique key); nullable foreign keys may represent no specified reference: a loan cannot refer to a student who does not exist.

A Customer table with primary key customer_id and an Order table whose foreign key points to it; an inner join gives 6 rows and a left join 7, because customer Ben has no orders
A foreign key links each order to its customer
词汇 训练
English 中文 拼音
database/ˈdeɪtəbeɪs/ 数据库 shù jù kù
database management system/ˈdeɪtəbeɪs ˈmænɪdʒmənt ˈsɪstəm/ 数据库管理系统 shù jù kù guǎn lǐ xì tǒng
data redundancy/ˈdeɪtə rɪˈdʌndənsi/ 数据冗余 shù jù rǒng yú
inconsistency/ˌɪnkənˈsɪstənsi/ 数据不一致 shù jù bù yī zhì
relational database/rɪˈleɪʃənl ˈdeɪtəbeɪs/ 关系数据库 guān xì shù jù kù
table/ˈteɪbl/ 表 biǎo
record/ˈrekɔːd/ 记录 jì lù
field/fiːld/ 字段 zì duàn
primary key/ˈpraɪməri kiː/ 主键 zhǔ jiàn
foreign key/ˈfɒrən kiː/ 外键 wài jiàn
composite key/ˈkɒmpəzɪt kiː/ 复合键 fù hé jiàn
referential integrity/ˌrefəˈrenʃl ɪnˈteɡrɪti/ 参照完整性 cān zhào wán zhěng xìng
3.3

数据库设计

English

Entities and relationships

An entity 实体 is a thing we store data about: a student, a book. An entity-relationship diagram 实体关系图 (ERD) shows the entities and how they are related.

An ER diagram: Student, with student_id (PK), name and year_group, makes many Loans; each Loan, with loan_id (PK), student_id (FK), book_id (FK) and date_out, is of one Book, with book_id (PK), title and author. Crow's feet mark the "many" ends
One student makes many loans; each loan is of one book
Relationship Meaning Example
one-to-one each A has one B a student and their locker
one-to-many one A has many B one student, many loans
many-to-many many A, many B students and books

A many-to-many relationship cannot be stored directly: it is split into two one-to-many relationships through a link table 连接表, here Loan.

Normalisation

Normalisation 规范化 organises tables to remove redundancy. Start from one unnormalised table:

Normalisation: one table where the customer name and phone repeat on every order is split into a separate ORDER table and CUSTOMER table, so each fact is stored once
Normalisation removes redundancy by splitting repeated data into its own table
order_id customer phone items
501 Li Na 1381 pen, ruler
502 Li Na 1381 pen
Form Rule Result
first normal form 第一范式 (1NF) every field holds one atomic value; no repeating groups one row per item: key (order_id, item)
second normal form 第二范式 (2NF) 1NF, and no non-key field depends on only part of a candidate key customer depends only on order_id: move it to an Order table; price depends only on item: move it to an Item table
third normal form 第三范式 (3NF) 2NF, with no transitive dependency of a non-key field on a candidate key phone depends on the customer, not the order: move it to a Customer table

Result in 3NF:

  • Customer(customer_id, name, phone)
  • Order(order_id, customer_id)
  • OrderLine(order_id, item_id, quantity)
  • Item(item_id, description, price)

Now Li Na's phone number is stored once. A short test for 3NF: every non-key field depends on "the key, the whole key, and nothing but the key".

Choosing data types

Each field needs a type, such as INTEGER, VARCHAR(50) (text up to 50 characters), DATE, BOOLEAN or DECIMAL(6,2). Phone numbers are stored as text, not integers: they can start with 0 and are never added up.

词汇 训练
English 中文 拼音
entity/ˈentɪti/ 实体 shí tǐ
entity-relationship diagram/ˈentɪti rɪˈleɪʃənʃɪp ˈdaɪəɡræm/ 实体关系图 shí tǐ guān xì tú
link table/lɪŋk ˈteɪbl/ 连接表 lián jiē biǎo
normalisation/ˌnɔːməlaɪˈzeɪʃn/ 规范化 guī fàn huà
first normal form/fɜːst ˈnɔːml fɔːm/ 第一范式 dì yī fàn shì
second normal form/ˈsekənd ˈnɔːml fɔːm/ 第二范式 dì èr fàn shì
third normal form/θɜːd ˈnɔːml fɔːm/ 第三范式 dì sān fàn shì
3.4

SQL

English

Querying data

SQL 结构化查询语言 (Structured Query Language) defines and queries relational databases. The examples use these tables:

Five steps in order: FROM and JOIN give all rows, WHERE drops rows, GROUP BY forms groups, HAVING drops groups, SELECT returns the answer.
The order a grouped query runs in: WHERE before the groups exist, HAVING after
Student
student_id name year_group
1 Ana 11
2 Ben 12
3 Chen 11
Book
book_id title author
10 Dune Herbert
11 Emma Austen
12 Holes Sachar
Loan
loan_id student_id book_id date_out
100 1 10 2026-09-01
101 1 12 2026-09-05
102 3 11 2026-09-06
SELECT name
FROM Student
WHERE year_group = 11
ORDER BY name DESC;

Result: Chen, Ana. WHERE filters rows; ORDER BY … DESC sorts Z to A.

SELECT Student.name, Book.title
FROM Loan
JOIN Student ON Loan.student_id = Student.student_id
JOIN Book ON Loan.book_id = Book.book_id;

Result: (Ana, Dune), (Ana, Holes), (Chen, Emma). A join 连接 combines tables by matching the foreign key with the primary key. Ben has no loans, so he does not appear.

SELECT student_id, COUNT(*) AS loans
FROM Loan
GROUP BY student_id;

Result: (1, 2), (3, 1). Aggregate functions 聚合函数 such as COUNT, SUM, AVG, MAX and MIN work on groups of rows.

Clause Use
WHERE filter rows: =, <>, >, LIKE 'D%', AND, OR
ORDER BY sort, ASC or DESC
GROUP BY make groups for aggregate functions
HAVING filter groups: HAVING COUNT(*) > 1

Changing data

INSERT INTO Book (book_id, title, author) VALUES (13, 'Wonder', 'Palacio');
UPDATE Student SET year_group = 12 WHERE student_id = 3;
DELETE FROM Loan WHERE loan_id = 100;

An UPDATE or DELETE without WHERE changes every row.

Transactions

A transaction 事务 is a group of operations that must all succeed or all fail, such as moving money: take it from one account and add it to another. Transactions follow ACID:

A transfer as one transaction: take 50 from account A and add 50 to account B; if both succeed, commit; if either fails, roll back so A gets its 50 back
All of it, or none of it
Property Meaning
atomicity all of it happens, or none of it
consistency the database moves from one valid state to another
isolation transactions running at once do not interfere
durability once committed, a change survives a crash
探索

一个客户可以产生多行匹配结果

每个客户的每笔匹配订单各产生一行;左连接还会为没有订单的客户保留一行NULL匹配结果。

词汇 训练
English 中文 拼音
SQL/ˌes kjuː ˈel/ 结构化查询语言 jié gòu huà chá xún yǔ yán
join/dʒɔɪn/ 连接 lián jiē
aggregate function/ˈæɡrɪɡeɪt ˈfʌŋkʃn/ 聚合函数 jù hé hán shù
transaction/trænˈsækʃn/ 事务 shì wù
3.5

练习

English
  1. State two problems of storing a school's data in one flat file.
  2. Define primary key and foreign key, with an example from the library tables.
  3. Explain why the many-to-many relationship between students and books needs the Loan table.
  4. A table has fields (booking_id, room, room_capacity, date). Explain why it is not in 3NF and normalise it.
  5. Write SQL to list the titles of all books by Austen.
  6. Write SQL to list the names of students in year 11 with the number of loans each has made.
  7. State the result of SELECT COUNT(*) FROM Loan WHERE book_id > 10; for the tables above.
  8. Write SQL to change the author of book 12 to 'L. Sachar'.
  9. Explain atomicity using a bank transfer.

Answers.

  1. E.g. data redundancy, the same student stored in many rows; inconsistency when one copy is updated and others are not; hard to search or control access.
  2. A primary key uniquely identifies each record, such as book_id in Book. A foreign key is a field holding another table's primary key, such as book_id in Loan.
  3. One student borrows many books and one book is borrowed by many students. A relational table cannot store this directly; the link table turns it into two one-to-many relationships, each loan linking one student and one book.
  4. room_capacity depends on room, a non-key field: a transitive dependency. Split into Booking(booking_id, room, date) and Room(room, room_capacity).
  5. SELECT title FROM Book WHERE author = 'Austen';
  6. SELECT Student.name, COUNT(*) FROM Student JOIN Loan ON Student.student_id = Loan.student_id WHERE Student.year_group = 11 GROUP BY Student.name; giving (Ana, 2), (Chen, 1).
  7. Loans 101 (book 12) and 102 (book 11): 2.
  8. UPDATE Book SET author = 'L. Sachar' WHERE book_id = 12;
  9. The money must both leave one account and arrive in the other; if the system fails part-way, the whole transaction is undone, so money is never lost or created.
  10. A graph database: people are nodes and friendships are links, so queries such as "friends of friends" follow links directly.
  11. E.g. a warehouse holds historical data from many sources, an operational database current data; a warehouse is mostly read for large analysis queries, an operational database handles many small updates.
3.6

考试技巧

English
  • Keys: say the primary key is unique for each record; a foreign key links to a primary key in another table.
  • In normalisation answers, name the dependency you are removing, then show the new tables with their keys.
  • Write SQL keywords in capitals, put text in single quotes, and end each statement with a semicolon.
  • In a join, always give the ON condition matching the foreign key to the primary key.
  • Check UPDATE and DELETE statements for a WHERE clause.
  • Learn ACID as four words with one-line meanings, and illustrate with a transfer.

更多 IB 计算机科学 SL 知识点

登录或创建账户

IGCSE, A-Level & AP