Skip to content

Blog 数据库 Schema

入门 约 15 分钟

你将构建什么

SQL script 那个创建完整 blog 数据库使用 three related 表: authors, posts, and comments, 已连接通过 foreign 键.

学习目标

  • 设计 Schema 使用 three related 表
  • Use 主要键 and foreign 键到 创建关系
  • Apply NOT NULL, UNIQUE, and DEFAULT constraints
  • Insert sample 数据到 所有 three 表

前置要求

  • 基础 SQL 语法
  • 理解的 表 and 行
  • 主要键 and foreign 键

步骤

  1. 1

    创建 authors 表

    开始通过创建 authors 表. 每个 author 有 auto-incrementing id, name, and email. email 应该是 唯一.

    代码
    CREATE TABLE authors (
      id     SERIAL PRIMARY KEY,
      name   TEXT NOT NULL,
      email  TEXT UNIQUE NOT NULL
    );

    预期结果

    authors 表是 创建使用 three 列 and appropriate constraints.

  2. 2

    创建 posts 表

    创建 posts 表. 每个 post belongs 到 author (外键), 有 title, 请求体, and creation timestamp.

    代码
    CREATE TABLE posts (
      id          SERIAL PRIMARY KEY,
      author_id   INTEGER REFERENCES authors(id),
      title       TEXT NOT NULL,
      body        TEXT NOT NULL,
      created_at  TIMESTAMP DEFAULT NOW()
    );

    预期结果

    posts 表是 创建使用外键链接每个 post 到 author.

  3. 3

    创建 comments 表

    创建 comments 表. 每个 comment belongs 到 post (外键) and 有 author name and 文本.

    代码
    CREATE TABLE comments (
      id         SERIAL PRIMARY KEY,
      post_id    INTEGER REFERENCES posts(id),
      author     TEXT NOT NULL,
      body       TEXT NOT NULL,
      created_at TIMESTAMP DEFAULT NOW()
    );

    预期结果

    comments 表是 创建, 链接到 posts 通过外键.

  4. 4

    Insert sample 数据

    Insert one author, one post 通过那个 author, and one comment on 那个 post. 这个测试那个你的 foreign 键工作正确地.

    代码
    INSERT INTO authors (name, email) VALUES ('Ada Lovelace', '[email protected]');
    
    INSERT INTO posts (author_id, title, body) VALUES (1, 'My First Post', 'Hello world!');
    
    INSERT INTO comments (post_id, author, body) VALUES (1, 'Grace', 'Great post!');

    预期结果

    Three 行是 inserted successfully, 确认关系工作.

  5. 5

    添加索引优化查询

    为频繁查询的列创建索引,提升查询性能。索引是数据库性能优化的首要手段,但需注意写操作的开销。

    代码
    -- Create indexes on frequently filtered columns
    CREATE INDEX idx_users_email ON users(email);
    CREATE INDEX idx_orders_user_id ON orders(user_id);
    CREATE INDEX idx_orders_created_at ON orders(created_at DESC);
    
    -- Verify the index is used
    EXPLAIN SELECT * FROM orders WHERE user_id = 42;

    预期结果

    EXPLAIN 输出显示使用 idx_orders_user_id 索引扫描而非全表扫描。

自己动手试试

你学到了什么

你设计 relational Schema 使用 three 表已连接通过 foreign 键, applied constraints, and inserted related 数据 — 基础的 每个 relational 数据库.

相关资源

相关课程

  • 表

    学习如何 创建表.

  • 关系

    学习关于 foreign 键 and 关系.

相关术语

  • 外键

    如何 foreign 键链接表.

  • 主键

    唯一行 identifiers.

相关术语

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

  • 外键

    如何 foreign 键链接表.

  • 主键

    唯一行 identifiers.

解读错误信息

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

查看错误

← 返回主题