Skip to content

表基础

📊 表的基本概念

什么是表?

在关系数据库中,表是存储数据的基本结构单元,它类似于 Excel 中的电子表格,由行和列组成。

表的特征

表的核心特征

  • 列的数量和顺序是固定的:一旦表创建,列的结构就确定了
  • 每列都有唯一的名称:用于标识不同的数据属性
  • 行的数量是可变的:可以随时增加、删除或修改数据记录
  • 行的顺序不确定:SQL 不保证表中行的显示顺序
  • 可能存在重复行:除非特别约束,表中可以有完全相同的行

🏗️ 数据类型基础

常用数据类型概览

数据类型说明适用场景示例值
integer整数类型商品编号、用户ID、计数123, -456
text文本类型商品名称、用户姓名、描述'iPhone 15', '张三'
numeric精确数值类型价格、金额、百分比999.99, 0.15
date日期类型生日、创建日期'2024-01-15'
time时间类型营业时间、会议时间'14:30:00'
timestamp日期时间类型创建时间、更新时间'2024-01-15 14:30:00'

数据类型的约束作用

数据类型的重要性

数据类型不仅仅是存储格式的定义,它还起到以下重要作用:

  1. 数据验证:确保输入的数据符合预期格式
  2. 存储优化:不同类型占用不同的存储空间
  3. 运算支持:数值类型支持数学运算,文本类型支持字符串操作
  4. 索引优化:合适的数据类型能提高查询性能

🔨 CREATE TABLE 详解

基本语法

sql
CREATE TABLE 表名 (
    列名1 数据类型1,
    列名2 数据类型2,
    列名3 数据类型3,
    ...
);

入门示例

让我们从最简单的例子开始:

sql
-- 创建第一个表
CREATE TABLE my_first_table (
    first_column text,
    second_column integer
);

示例分析:

  • my_first_table:表名
  • first_column text:第一列,文本类型
  • second_column integer:第二列,整数类型
  • 列之间用逗号分隔
  • 整个列定义用括号包围

实际业务示例

商品表设计

sql
-- 创建商品表
CREATE TABLE products (
    product_no integer,      -- 商品编号
    name text,              -- 商品名称  
    price numeric(10,2),    -- 商品价格(最大10位,小数点后2位)
    description text,       -- 商品描述
    category text,          -- 商品分类
    stock_quantity integer, -- 库存数量
    created_date date       -- 创建日期
);

用户表设计

sql
-- 创建用户表
CREATE TABLE users (
    user_id integer,        -- 用户ID
    username text,          -- 用户名
    email text,            -- 邮箱
    full_name text,        -- 全名
    birth_date date,       -- 生日
    registration_time timestamp, -- 注册时间
    is_active boolean      -- 是否激活
);

订单表设计

sql
-- 创建订单表
CREATE TABLE orders (
    order_id integer,       -- 订单ID
    user_id integer,        -- 用户ID(外键)
    order_date date,        -- 订单日期
    total_amount numeric(12,2), -- 订单总金额
    status text,           -- 订单状态
    shipping_address text, -- 配送地址
    created_at timestamp   -- 创建时间
);

创建表的完整示例

sql
-- 创建员工表(基础版本)
CREATE TABLE employees (
    emp_id integer,
    name text,
    salary numeric
);
sql
-- 创建员工表(完整版本)
CREATE TABLE employees (
    emp_id integer,           -- 员工ID
    first_name text,          -- 名
    last_name text,           -- 姓
    email text,               -- 邮箱
    phone text,               -- 电话
    hire_date date,           -- 入职日期
    job_title text,           -- 职位
    salary numeric(10,2),     -- 薪资
    department_id integer,    -- 部门ID
    manager_id integer,       -- 经理ID
    is_active boolean,        -- 是否在职
    created_at timestamp,     -- 记录创建时间
    updated_at timestamp      -- 记录更新时间
);

🗑️ DROP TABLE 详解

基本语法

sql
DROP TABLE 表名;

基础删除示例

sql
-- 删除单个表
DROP TABLE my_first_table;

-- 删除多个表
DROP TABLE products;
DROP TABLE users;
DROP TABLE orders;

安全删除方式

IF EXISTS 条件删除

sql
-- 安全删除:如果表存在则删除,不存在也不报错
DROP TABLE IF EXISTS my_first_table;
DROP TABLE IF EXISTS products;

删除前备份

sql
-- 删除前先备份数据
CREATE TABLE products_backup AS SELECT * FROM products;

-- 然后删除原表
DROP TABLE products;

-- 如果需要还原
CREATE TABLE products AS SELECT * FROM products_backup;

删除表的注意事项

删除表的风险

  1. 数据丢失:删除表会永久丢失所有数据
  2. 依赖关系:有外键依赖的表不能直接删除
  3. 权限要求:需要足够的数据库权限
  4. 不可恢复:删除操作通常不可撤销

批量删除脚本示例

sql
-- 开发环境:重建整个数据库架构
-- 注意:这会删除所有数据!

-- 删除顺序很重要:先删除依赖表,后删除被依赖表
DROP TABLE IF EXISTS order_items;    -- 订单明细表
DROP TABLE IF EXISTS orders;         -- 订单表  
DROP TABLE IF EXISTS products;       -- 商品表
DROP TABLE IF EXISTS users;          -- 用户表
DROP TABLE IF EXISTS categories;     -- 分类表

-- 重新创建表结构
CREATE TABLE categories (
    category_id integer,
    category_name text,
    description text
);

CREATE TABLE products (
    product_id integer,
    product_name text,
    category_id integer,
    price numeric(10,2)
);

-- ... 其他表的创建语句

🎨 表设计最佳实践

命名规范

表命名规范

表命名建议

  1. 使用复数形式productsusersorders
  2. 使用小写字母user_profiles 而不是 UserProfiles
  3. 使用下划线分隔order_items 而不是 orderitems
  4. 名称要有意义employees 而不是 empe

列命名规范

命名类型推荐格式示例
主键表名_iduser_idproduct_id
外键关联表名_idcategory_iduser_id
布尔值is_xxxis_activeis_deleted
时间戳xxx_atcreated_atupdated_at
日期xxx_datebirth_dateorder_date

💡 性能优化提示

列数限制

PostgreSQL 列数限制

  • 理论限制:250-1600列(取决于列类型)
  • 实际建议:一般不超过50-100列
  • 设计原则:如果列数过多,考虑表规范化

存储优化

sql
-- 数据类型选择对存储的影响
CREATE TABLE storage_example (
    -- 整数类型选择
    small_int smallint,      -- 2字节:-32,768 到 32,767
    normal_int integer,      -- 4字节:-2^31 到 2^31-1  
    big_int bigint,         -- 8字节:-2^63 到 2^63-1
    
    -- 文本类型选择
    short_text varchar(50),  -- 变长,最大50字符
    long_text text,         -- 变长,无限制
    
    -- 数值类型选择
    exact_decimal numeric(10,2),  -- 精确小数
    approx_decimal real          -- 近似小数(更节省空间)
);