Skip to content

Relational Model

表, 行, 列, 键, and mathematical 基础的 relational 数据库.

你将学到

  • 如何数据是 组织到 表, 行, and 列
  • 什么主要键 and foreign 键是 and 为什么它们 matter
  • difference 之间 Schema and 表
  • 如何 relational model 连接表 通过关系

概念讲解

表、行和列

The relational model, introduced by Edgar F. Codd in 1970, organizes data into tables (also called relations). Each table has a set of named columns (attributes) that define what kind of data is stored, and each row (tuple) is a single record. For example, a 用户 table might have columns id, name, and email, and each row represents one user.

Primary Keys

A primary key is a column (or combination of columns) that uniquely identifies each row in a table. No two rows can share the same primary key value, and it can never be NULL. Common choices are an auto-incrementing integer (id) or a UUID. The primary key is the anchor that lets you refer to a specific row from anywhere else.

Foreign Keys and Relationships

A foreign key is a column in one table that references the primary key of another table. This is how the relational model expresses relationships. For example, an 顺序 table might have a user_id column that references 用户.id. The database enforces this link — you cannot insert an order with a user_id that does not exist in the 用户 table.

Schema

A schema is the blueprint of your database: it defines every table, every column (with its data type), every constraint, and every relationship. The schema is fixed at design time (though it can be changed with migrations). This rigidity is a feature — it guarantees that every row conforms to the expected shape, preventing a whole class of data-quality bugs.

示例代码

              -- users table with a primary key
CREATE TABLE users (
  id    SERIAL PRIMARY KEY,
  name  VARCHAR(100) NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL
);

-- orders table with a foreign key to users
CREATE TABLE orders (
  id        SERIAL PRIMARY KEY,
  user_id   INTEGER NOT NULL REFERENCES users(id),
  total     DECIMAL(10, 2) NOT NULL,
  created_at TIMESTAMP DEFAULT NOW()
);
            

SERIAL auto-generates integer IDs. REFERENCES 用户(id) 创建外键 — 每个顺序必须 belong 到真实用户.

动手试一试

常见错误

错误写法

Forgetting 到定义主键

正确做法

每个表 应该有 主键. 不使用 one, 你 cannot reliably identify or 更新 individual 行.

错误写法

存储关系 as comma-separated 值

正确做法

Use 外键列 or junction 表相反. CSV in 单个列 breaks 连接 and integrity.

练习 Relational Model

2 个练习

练习 Relational Model

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误