# 解班客数据库设计文档

## 1. 概述

### 1.1 项目简介
解班客是一个综合性的社交旅行平台，融合了结伴旅行、动物认领、商家服务等多种功能。本文档详细描述了支撑整个平台运行的数据库设计方案。

### 1.2 设计原则
- **数据一致性**：确保数据的完整性和一致性
- **性能优化**：合理设计索引，优化查询性能
- **扩展性**：支持业务快速发展和功能扩展
- **安全性**：敏感数据加密存储，权限控制
- **可维护性**：清晰的表结构和命名规范

### 1.3 技术选型
- **主数据库**：MySQL 8.0
- **缓存数据库**：Redis 6.0
- **文件存储**：腾讯云COS

### 1.4 数据库配置

本项目使用统一的数据库实例，所有环境共享同一个数据库配置：

#### 数据库连接信息
- **主机地址**：nj-cdb-3pwh2kz1.sql.tencentcdb.com
- **端口**：20784
- **用户名**：jiebanke
- **密码**：aiot741$12346
- **数据库名**：jbkdata
- **连接池大小**：10
- **字符集**：utf8mb4
- **时区**：+08:00

#### 环境变量配置
```bash
# 数据库配置
DB_HOST=nj-cdb-3pwh2kz1.sql.tencentcdb.com
DB_PORT=20784
DB_USER=jiebanke
DB_PASSWORD=aiot741$12346
DB_NAME=jbkdata
```

#### 连接配置示例
```javascript
// Node.js 连接配置
const dbConfig = {
  host: process.env.DB_HOST || 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
  port: process.env.DB_PORT || 20784,
  user: process.env.DB_USER || 'jiebanke',
  password: process.env.DB_PASSWORD || 'aiot741$12346',
  database: process.env.DB_NAME || 'jbkdata',
  connectionLimit: 10,
  charset: 'utf8mb4',
  timezone: '+08:00'
};
```

## 2. 数据库架构

### 2.1 整体架构

```mermaid
graph TB
    subgraph "应用层"
        A[小程序App]
        B[管理后台]
        C[官方网站]
        D[后端API]
    end
    
    subgraph "数据访问层"
        E[ORM层 - Sequelize]
        F[缓存层 - Redis]
    end
    
    subgraph "数据存储层"
        G[MySQL数据库<br/>jbkdata]
        H[文件存储 - 腾讯云COS]
    end
    
    A --> D
    B --> D
    C --> D
    D --> E
    D --> F
    E --> G
    F --> G
    D --> H
```

### 2.2 数据库连接架构
```mermaid
graph TB
    subgraph "应用服务"
        A[小程序API]
        B[管理后台API]
        C[官网API]
    end
    
    subgraph "连接池管理"
        D[连接池<br/>最大连接数: 10]
    end
    
    subgraph "腾讯云数据库"
        E[MySQL 8.0<br/>nj-cdb-3pwh2kz1.sql.tencentcdb.com:20784<br/>数据库: jbkdata]
    end
    
    A --> D
    B --> D
    C --> D
    D --> E
## 3. 数据库设计原则

### 3.1 表设计规范
- **命名规范**：使用小写字母和下划线，表名使用复数形式
- **主键设计**：统一使用自增整型主键 `id`
- **时间字段**：统一使用 `created_at` 和 `updated_at`
- **软删除**：使用 `deleted_at` 字段实现软删除
- **状态字段**：使用 `status` 字段管理记录状态

### 3.2 索引设计原则
- **主键索引**：每个表必须有主键
- **唯一索引**：对唯一性约束字段创建唯一索引
- **复合索引**：根据查询场景创建合适的复合索引
- **外键索引**：对外键字段创建索引

### 3.3 数据类型规范
- **整型**：使用 `INT` 或 `BIGINT`
- **字符串**：使用 `VARCHAR` 或 `TEXT`
- **时间**：使用 `TIMESTAMP` 或 `DATETIME`
- **枚举**：使用 `ENUM` 或 `TINYINT`
- **布尔**：使用 `TINYINT(1)`

## 4. 数据库ER图

```mermaid
erDiagram
    USERS ||--o{ TRAVEL_PLANS : creates
    USERS ||--o{ TRAVEL_MATCHES : participates
    USERS ||--o{ ANIMAL_CLAIMS : claims
    USERS ||--o{ ORDERS : places
    USERS ||--o{ REVIEWS : writes
    USERS ||--o{ MESSAGES : sends
    USERS ||--o{ USER_INTERESTS : has
    
    MERCHANTS ||--o{ ANIMALS : manages
    MERCHANTS ||--o{ PRODUCTS : sells
    MERCHANTS ||--o{ ACTIVITIES : organizes
    MERCHANTS ||--o{ ORDERS : receives
    
    TRAVEL_PLANS ||--o{ TRAVEL_MATCHES : generates
    TRAVEL_PLANS ||--o{ TRAVEL_INVITATIONS : has
    
    ANIMALS ||--o{ ANIMAL_CLAIMS : claimed_by
    ANIMALS ||--o{ ANIMAL_UPDATES : has
    
    PRODUCTS ||--o{ ORDER_ITEMS : contains
    ORDERS ||--o{ ORDER_ITEMS : includes
    ORDERS ||--o{ PAYMENTS : has
    
    ACTIVITIES ||--o{ ACTIVITY_REGISTRATIONS : registers
    
    ADMINS ||--o{ ADMIN_LOGS : creates
    
    USERS {
        int id PK
        string openid UK
        string nickname
        string avatar
        enum gender
        date birthday
        string phone UK
        string email UK
        int travel_count
        int animal_claim_count
        enum status
        timestamp created_at
        timestamp updated_at
    }
    
    MERCHANTS {
        int id PK
        int user_id FK
        enum merchant_type
        string business_name
        string business_license UK
        string contact_person
        string contact_phone
        text address
        text description
        enum status
        timestamp created_at
        timestamp updated_at
    }
    
    TRAVEL_PLANS {
        int id PK
        int user_id FK
        string destination
        date start_date
        date end_date
        decimal budget
        text interests
        text description
        enum visibility
        int max_participants
        int current_participants
        enum status
        timestamp created_at
        timestamp updated_at
    }
    
    ANIMALS {
        int id PK
        int merchant_id FK
        string name
        enum type
        string breed
        int age
        enum gender
        text description
        json images
        decimal price
        string farm_location
        enum status
        int claim_count
        timestamp created_at
        timestamp updated_at
    }
    
    ORDERS {
        int id PK
        string order_number UK
        int user_id FK
        int merchant_id FK
        enum order_type
        decimal total_amount
        enum status
        json delivery_info
        timestamp ordered_at
        timestamp completed_at
        timestamp created_at
        timestamp updated_at
    }
```

## 📋 核心表结构设计

### 1. 用户管理模块

#### 1.1 用户表 (users)
```sql
CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '用户ID',
    real_name VARCHAR(50) COMMENT '真实姓名',
    nickname VARCHAR(50) COMMENT '用户昵称',
    avatar_url VARCHAR(255) COMMENT '头像URL',
    user_type ENUM('regular','vip','premium') DEFAULT 'regular' COMMENT '用户类型',
    status ENUM('active','inactive','banned') DEFAULT 'active' COMMENT '用户状态',
    balance DECIMAL(10,2) DEFAULT 0.00 COMMENT '账户余额',
    points INT DEFAULT 0 COMMENT '积分',
    level INT DEFAULT 1 COMMENT '用户等级',
    last_login_at TIMESTAMP COMMENT '最后登录时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    deleted_at TIMESTAMP NULL COMMENT '删除时间',
    
    INDEX idx_status (status),
    INDEX idx_user_type (user_type),
    INDEX idx_level (level),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户基础信息表';
```

#### 1.2 管理员表 (admins)
```sql
CREATE TABLE admins (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '管理员ID',
    username VARCHAR(50) UNIQUE NOT NULL COMMENT '用户名',
    password VARCHAR(255) NOT NULL COMMENT '密码',
    email VARCHAR(100) UNIQUE COMMENT '邮箱',
    nickname VARCHAR(50) COMMENT '昵称',
    avatar VARCHAR(255) COMMENT '头像',
    role ENUM('super_admin','admin','editor') DEFAULT 'admin' COMMENT '角色',
    status ENUM('active','inactive') DEFAULT 'active' COMMENT '状态',
    last_login TIMESTAMP COMMENT '最后登录时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_username (username),
    INDEX idx_email (email),
    INDEX idx_role (role),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='管理员表';
```

### 2. 商家管理模块

#### 2.1 商家表 (merchants)
```sql
CREATE TABLE merchants (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '商家ID',
    user_id INT NOT NULL COMMENT '关联用户ID',
    name VARCHAR(100) NOT NULL COMMENT '商家名称',
    description TEXT COMMENT '商家描述',
    address VARCHAR(255) COMMENT '地址',
    latitude DECIMAL(10,8) COMMENT '纬度',
    longitude DECIMAL(11,8) COMMENT '经度',
    contact_phone VARCHAR(20) COMMENT '联系电话',
    business_hours VARCHAR(100) COMMENT '营业时间',
    images JSON COMMENT '商家图片',
    rating DECIMAL(3,2) DEFAULT 0.00 COMMENT '评分',
    review_count INT DEFAULT 0 COMMENT '评价数量',
    status ENUM('active','inactive','pending') DEFAULT 'pending' COMMENT '状态',
    verified_at TIMESTAMP NULL COMMENT '认证时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_status (status),
    INDEX idx_rating (rating),
    INDEX idx_location (latitude, longitude)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商家信息表';
```

### 3. 动物认领模块

#### 3.1 动物表 (animals)
```sql
CREATE TABLE animals (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '动物ID',
    name VARCHAR(50) NOT NULL COMMENT '动物名称',
    type VARCHAR(30) NOT NULL COMMENT '动物类型',
    breed VARCHAR(50) COMMENT '品种',
    age INT COMMENT '年龄',
    gender ENUM('male','female','unknown') DEFAULT 'unknown' COMMENT '性别',
    description TEXT COMMENT '描述',
    images JSON COMMENT '图片',
    price DECIMAL(10,2) NOT NULL COMMENT '认领价格',
    daily_cost DECIMAL(8,2) COMMENT '日常费用',
    location VARCHAR(100) COMMENT '所在地',
    farmer_id INT COMMENT '农场主ID',
    status ENUM('available','claimed','unavailable') DEFAULT 'available' COMMENT '状态',
    health_status VARCHAR(50) COMMENT '健康状态',
    vaccination_records JSON COMMENT '疫苗记录',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    deleted_at TIMESTAMP NULL COMMENT '删除时间',
    
    FOREIGN KEY (farmer_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_farmer_id (farmer_id),
    INDEX idx_type (type),
    INDEX idx_status (status),
    INDEX idx_price (price)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='动物信息表';
```

#### 3.2 动物认领表 (animal_claims)
```sql
CREATE TABLE animal_claims (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '认领ID',
    animal_id INT NOT NULL COMMENT '动物ID',
    user_id INT NOT NULL COMMENT '用户ID',
    contact_info VARCHAR(100) COMMENT '联系信息',
    status ENUM('pending','approved','rejected','cancelled') DEFAULT 'pending' COMMENT '状态',
    reviewed_by INT COMMENT '审核人ID',
    reviewed_at TIMESTAMP NULL COMMENT '审核时间',
    review_note TEXT COMMENT '审核备注',
    start_date DATE COMMENT '开始日期',
    end_date DATE COMMENT '结束日期',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    deleted_at TIMESTAMP NULL COMMENT '删除时间',
    
    FOREIGN KEY (animal_id) REFERENCES animals(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_animal_id (animal_id),
    INDEX idx_user_id (user_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='动物认领表';
```

### 4. 旅行计划模块

#### 4.1 旅行计划表 (travel_plans)
```sql
CREATE TABLE travel_plans (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '计划ID',
    title VARCHAR(100) NOT NULL COMMENT '计划标题',
    destination VARCHAR(100) NOT NULL COMMENT '目的地',
    description TEXT COMMENT '描述',
    start_date DATE NOT NULL COMMENT '开始日期',
    end_date DATE NOT NULL COMMENT '结束日期',
    max_participants INT DEFAULT 10 COMMENT '最大参与人数',
    current_participants INT DEFAULT 0 COMMENT '当前参与人数',
    price_per_person DECIMAL(10,2) NOT NULL COMMENT '每人价格',
    includes JSON COMMENT '包含项目',
    excludes JSON COMMENT '不包含项目',
    itinerary JSON COMMENT '行程安排',
    images JSON COMMENT '图片',
    requirements TEXT COMMENT '参与要求',
    created_by INT NOT NULL COMMENT '创建者ID',
    status ENUM('draft','published','cancelled','completed') DEFAULT 'draft' COMMENT '状态',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_created_by (created_by),
    INDEX idx_destination (destination),
    INDEX idx_status (status),
    INDEX idx_start_date (start_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='旅行计划表';
```

#### 4.2 旅行报名表 (travel_registrations)
```sql
CREATE TABLE travel_registrations (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '报名ID',
    travel_plan_id INT NOT NULL COMMENT '旅行计划ID',
    user_id INT NOT NULL COMMENT '用户ID',
    participants INT DEFAULT 1 COMMENT '参与人数',
    message TEXT COMMENT '留言',
    emergency_contact VARCHAR(50) COMMENT '紧急联系人',
    emergency_phone VARCHAR(20) COMMENT '紧急联系电话',
    status ENUM('pending','approved','rejected','cancelled') DEFAULT 'pending' COMMENT '状态',
    reject_reason TEXT COMMENT '拒绝原因',
    applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间',
    responded_at TIMESTAMP NULL COMMENT '响应时间',
    
    FOREIGN KEY (travel_plan_id) REFERENCES travel_plans(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_travel_plan_id (travel_plan_id),
    INDEX idx_user_id (user_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='旅行报名表';
```

### 5. 花卉产品模块

#### 5.1 花卉表 (flowers)
```sql
CREATE TABLE flowers (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '花卉ID',
    name VARCHAR(100) NOT NULL COMMENT '花卉名称',
    scientific_name VARCHAR(100) COMMENT '学名',
    category VARCHAR(50) COMMENT '分类',
    color VARCHAR(30) COMMENT '颜色',
    bloom_season VARCHAR(50) COMMENT '花期',
    care_level ENUM('easy','medium','hard') DEFAULT 'medium' COMMENT '养护难度',
    description TEXT COMMENT '描述',
    care_instructions TEXT COMMENT '养护说明',
    image VARCHAR(255) COMMENT '主图片',
    images JSON COMMENT '图片集',
    price DECIMAL(8,2) NOT NULL COMMENT '价格',
    stock_quantity INT DEFAULT 0 COMMENT '库存数量',
    farmer_id INT COMMENT '农场主ID',
    status ENUM('available','out_of_stock','discontinued') DEFAULT 'available' COMMENT '状态',
    seasonal_availability JSON COMMENT '季节性供应',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (farmer_id) REFERENCES users(id) ON DELETE SET NULL,
    INDEX idx_farmer_id (farmer_id),
    INDEX idx_category (category),
    INDEX idx_status (status),
    INDEX idx_price (price)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='花卉产品表';
```

### 6. 订单管理模块

#### 6.1 订单表 (orders)
```sql
CREATE TABLE orders (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '订单ID',
    order_number VARCHAR(32) UNIQUE NOT NULL COMMENT '订单号',
    user_id INT NOT NULL COMMENT '用户ID',
    total_amount DECIMAL(15,2) NOT NULL COMMENT '订单总金额',
    status ENUM('pending','paid','shipped','delivered','cancelled','refunded') DEFAULT 'pending' COMMENT '订单状态',
    payment_status ENUM('unpaid','paid','refunded','partial_refund') DEFAULT 'unpaid' COMMENT '支付状态',
    payment_method VARCHAR(20) COMMENT '支付方式',
    payment_time TIMESTAMP NULL COMMENT '支付时间',
    shipping_address JSON COMMENT '收货地址',
    contact_info JSON COMMENT '联系信息',
    notes TEXT COMMENT '备注',
    ordered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '下单时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_order_number (order_number),
    INDEX idx_status (status),
    INDEX idx_payment_status (payment_status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单表';
```

#### 6.2 支付表 (payments)
```sql
CREATE TABLE payments (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '支付ID',
    order_id INT NOT NULL COMMENT '订单ID',
    user_id INT NOT NULL COMMENT '用户ID',
    amount DECIMAL(15,2) NOT NULL COMMENT '支付金额',
    payment_method ENUM('wechat','alipay','balance','points') NOT NULL COMMENT '支付方式',
    status ENUM('pending','success','failed','cancelled','refunded') DEFAULT 'pending' COMMENT '支付状态',
    transaction_id VARCHAR(100) COMMENT '交易流水号',
    paid_amount DECIMAL(15,2) COMMENT '实际支付金额',
    paid_at TIMESTAMP NULL COMMENT '支付时间',
    
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_order_id (order_id),
    INDEX idx_user_id (user_id),
    INDEX idx_status (status),
    INDEX idx_transaction_id (transaction_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付记录表';
```

#### 6.3 退款表 (refunds)
```sql
CREATE TABLE refunds (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '退款ID',
    payment_id INT NOT NULL COMMENT '支付ID',
    user_id INT NOT NULL COMMENT '用户ID',
    refund_amount DECIMAL(15,2) NOT NULL COMMENT '退款金额',
    refund_reason VARCHAR(255) NOT NULL COMMENT '退款原因',
    status ENUM('pending','processing','completed','rejected') DEFAULT 'pending' COMMENT '退款状态',
    processed_by INT COMMENT '处理人ID',
    processed_at TIMESTAMP NULL COMMENT '处理时间',
    process_remark TEXT COMMENT '处理备注',
    refund_transaction_id VARCHAR(100) COMMENT '退款交易号',
    refunded_at TIMESTAMP NULL COMMENT '退款完成时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    deleted_at TIMESTAMP NULL COMMENT '删除时间',
    
    FOREIGN KEY (payment_id) REFERENCES payments(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_payment_id (payment_id),
    INDEX idx_user_id (user_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='退款记录表';
```

### 7. 系统辅助表

#### 7.1 邮箱验证表 (email_verifications)
```sql
CREATE TABLE email_verifications (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '验证ID',
    email VARCHAR(100) NOT NULL COMMENT '邮箱地址',
    code VARCHAR(10) NOT NULL COMMENT '验证码',
    type ENUM('register','reset_password','change_email') NOT NULL COMMENT '验证类型',
    expires_at TIMESTAMP NOT NULL COMMENT '过期时间',
    used_at TIMESTAMP NULL COMMENT '使用时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    INDEX idx_email (email),
    INDEX idx_code (code),
    INDEX idx_expires_at (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='邮箱验证表';
```

#### 7.2 密码重置表 (password_resets)
```sql
CREATE TABLE password_resets (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '重置ID',
    user_id INT NOT NULL COMMENT '用户ID',
    token VARCHAR(100) NOT NULL COMMENT '重置令牌',
    expires_at TIMESTAMP NOT NULL COMMENT '过期时间',
    used_at TIMESTAMP NULL COMMENT '使用时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_token (token),
    INDEX idx_expires_at (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='密码重置表';
```

#### 7.3 登录尝试表 (login_attempts)
```sql
CREATE TABLE login_attempts (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '尝试ID',
    identifier VARCHAR(100) NOT NULL COMMENT '标识符(用户名/邮箱/手机)',
    ip_address VARCHAR(45) NOT NULL COMMENT 'IP地址',
    user_agent TEXT COMMENT '用户代理',
    success TINYINT(1) DEFAULT 0 COMMENT '是否成功',
    failure_reason VARCHAR(100) COMMENT '失败原因',
    attempted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '尝试时间',
    
    INDEX idx_identifier (identifier),
    INDEX idx_ip_address (ip_address),
    INDEX idx_attempted_at (attempted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='登录尝试记录表';
```

## 5. 表关系图

### 5.1 外键关系
根据实际数据库结构，以下是表之间的外键关系：

```mermaid
erDiagram
    users ||--o{ animal_claims : "user_id"
    users ||--o{ animals : "farmer_id"
    users ||--o{ flowers : "farmer_id"
    users ||--o{ merchants : "user_id"
    users ||--o{ orders : "user_id"
    users ||--o{ password_resets : "user_id"
    users ||--o{ payments : "user_id"
    users ||--o{ refunds : "user_id"
    users ||--o{ travel_plans : "created_by"
    users ||--o{ travel_registrations : "user_id"
    
    animals ||--o{ animal_claims : "animal_id"
    orders ||--o{ payments : "order_id"
    payments ||--o{ refunds : "payment_id"
    travel_plans ||--o{ travel_registrations : "travel_plan_id"
```

### 5.2 核心业务关系说明

1. **用户中心关系**：
   - 用户可以认领多个动物 (users → animal_claims)
   - 用户可以作为农场主管理动物和花卉 (users → animals/flowers)
   - 用户可以注册为商家 (users → merchants)
   - 用户可以下订单和支付 (users → orders → payments)

2. **旅行业务关系**：
   - 用户创建旅行计划 (users → travel_plans)
   - 其他用户报名参与旅行 (users → travel_registrations)
   - 旅行计划与报名记录关联 (travel_plans → travel_registrations)

3. **交易业务关系**：
   - 订单关联支付记录 (orders → payments)
   - 支付记录可以产生退款 (payments → refunds)
   - 所有交易都关联到用户 (users → orders/payments/refunds)

### 2. 商家管理模块

#### 2.1 商家表 (merchants)
```sql
CREATE TABLE merchants (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '商家ID',
    user_id INT NOT NULL COMMENT '关联用户ID',
    merchant_type ENUM('flower_shop', 'farm', 'activity_organizer', 'travel_agency') NOT NULL COMMENT '商家类型',
    business_name VARCHAR(100) NOT NULL COMMENT '商家名称',
    business_license VARCHAR(50) UNIQUE NOT NULL COMMENT '营业执照号',
    contact_person VARCHAR(50) NOT NULL COMMENT '联系人姓名',
    contact_phone VARCHAR(20) NOT NULL COMMENT '联系电话',
    address TEXT COMMENT '经营地址',
    description TEXT COMMENT '商家描述',
    business_hours VARCHAR(100) COMMENT '营业时间',
    rating DECIMAL(3,2) DEFAULT 5.00 COMMENT '商家评分',
    review_count INT DEFAULT 0 COMMENT '评价数量',
    status ENUM('pending', 'approved', 'rejected', 'suspended') DEFAULT 'pending' COMMENT '审核状态',
    verified_at TIMESTAMP COMMENT '认证时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY uk_business_license (business_license),
    INDEX idx_user_id (user_id),
    INDEX idx_merchant_type (merchant_type),
    INDEX idx_status (status),
    INDEX idx_rating (rating)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商家信息表';
```

### 3. 旅行结伴模块

#### 3.1 旅行计划表 (travel_plans)
```sql
CREATE TABLE travel_plans (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '旅行计划ID',
    user_id INT NOT NULL COMMENT '发起用户ID',
    title VARCHAR(100) NOT NULL COMMENT '旅行标题',
    destination VARCHAR(100) NOT NULL COMMENT '目的地',
    start_date DATE NOT NULL COMMENT '开始日期',
    end_date DATE NOT NULL COMMENT '结束日期',
    budget DECIMAL(10,2) COMMENT '预算金额',
    interests TEXT COMMENT '兴趣偏好',
    description TEXT COMMENT '行程描述',
    requirements TEXT COMMENT '同行要求',
    visibility ENUM('public', 'friends', 'private') DEFAULT 'public' COMMENT '可见性',
    max_participants INT DEFAULT 4 COMMENT '最大参与人数',
    current_participants INT DEFAULT 1 COMMENT '当前参与人数',
    gender_preference ENUM('male', 'female', 'mixed', 'no_preference') DEFAULT 'no_preference' COMMENT '性别偏好',
    age_min INT COMMENT '最小年龄要求',
    age_max INT COMMENT '最大年龄要求',
    status ENUM('active', 'full', 'completed', 'cancelled') DEFAULT 'active' COMMENT '计划状态',
    view_count INT DEFAULT 0 COMMENT '浏览次数',
    like_count INT DEFAULT 0 COMMENT '点赞次数',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_destination (destination),
    INDEX idx_date_range (start_date, end_date),
    INDEX idx_status (status),
    INDEX idx_budget (budget),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='旅行计划表';
```

#### 3.2 旅行匹配表 (travel_matches)
```sql
CREATE TABLE travel_matches (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '匹配ID',
    travel_plan_id INT NOT NULL COMMENT '旅行计划ID',
    user_id INT NOT NULL COMMENT '申请用户ID',
    message TEXT COMMENT '申请留言',
    status ENUM('pending', 'approved', 'rejected', 'cancelled') DEFAULT 'pending' COMMENT '申请状态',
    applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间',
    responded_at TIMESTAMP COMMENT '响应时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (travel_plan_id) REFERENCES travel_plans(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY uk_plan_user (travel_plan_id, user_id),
    INDEX idx_travel_plan_id (travel_plan_id),
    INDEX idx_user_id (user_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='旅行匹配申请表';
```

### 4. 动物认领模块

#### 4.1 动物信息表 (animals)
```sql
CREATE TABLE animals (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '动物ID',
    merchant_id INT NOT NULL COMMENT '所属商家ID',
    name VARCHAR(50) NOT NULL COMMENT '动物名称',
    type ENUM('cow', 'sheep', 'pig', 'chicken', 'duck', 'goat', 'rabbit') NOT NULL COMMENT '动物类型',
    breed VARCHAR(50) COMMENT '品种',
    age INT COMMENT '年龄（月）',
    gender ENUM('male', 'female') COMMENT '性别',
    weight DECIMAL(5,2) COMMENT '体重（公斤）',
    color VARCHAR(50) COMMENT '毛色',
    personality TEXT COMMENT '性格特点',
    description TEXT COMMENT '动物描述',
    images JSON COMMENT '动物图片数组',
    videos JSON COMMENT '动物视频数组',
    price DECIMAL(10,2) NOT NULL COMMENT '认领价格（月）',
    farm_location VARCHAR(100) COMMENT '农场位置',
    farm_environment TEXT COMMENT '农场环境描述',
    feeding_info TEXT COMMENT '喂养信息',
    health_status ENUM('healthy', 'sick', 'recovering') DEFAULT 'healthy' COMMENT '健康状态',
    vaccination_record JSON COMMENT '疫苗接种记录',
    status ENUM('available', 'claimed', 'unavailable', 'sold') DEFAULT 'available' COMMENT '动物状态',
    claim_count INT DEFAULT 0 COMMENT '被认领次数',
    rating DECIMAL(3,2) DEFAULT 5.00 COMMENT '动物评分',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (merchant_id) REFERENCES merchants(id) ON DELETE CASCADE,
    INDEX idx_merchant_id (merchant_id),
    INDEX idx_type (type),
    INDEX idx_status (status),
    INDEX idx_price (price),
    INDEX idx_age (age),
    INDEX idx_rating (rating)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='动物信息表';
```

#### 4.2 动物认领表 (animal_claims)
```sql
CREATE TABLE animal_claims (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '认领ID',
    user_id INT NOT NULL COMMENT '认领用户ID',
    animal_id INT NOT NULL COMMENT '动物ID',
    claim_name VARCHAR(50) COMMENT '认领后的动物名称',
    duration INT NOT NULL COMMENT '认领时长（月）',
    monthly_price DECIMAL(10,2) NOT NULL COMMENT '月费用',
    total_amount DECIMAL(10,2) NOT NULL COMMENT '总金额',
    start_date DATE NOT NULL COMMENT '认领开始日期',
    end_date DATE NOT NULL COMMENT '认领结束日期',
    auto_renew BOOLEAN DEFAULT FALSE COMMENT '是否自动续费',
    visit_count INT DEFAULT 0 COMMENT '探访次数',
    last_visit_date DATE COMMENT '最后探访日期',
    status ENUM('active', 'expired', 'cancelled', 'completed') DEFAULT 'active' COMMENT '认领状态',
    message TEXT COMMENT '认领留言',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (animal_id) REFERENCES animals(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_animal_id (animal_id),
    INDEX idx_status (status),
    INDEX idx_date_range (start_date, end_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='动物认领表';
```

#### 4.3 动物更新记录表 (animal_updates)
```sql
CREATE TABLE animal_updates (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '更新记录ID',
    animal_id INT NOT NULL COMMENT '动物ID',
    claim_id INT COMMENT '认领ID',
    update_type ENUM('growth', 'health', 'feeding', 'activity', 'photo', 'video') NOT NULL COMMENT '更新类型',
    title VARCHAR(100) NOT NULL COMMENT '更新标题',
    content TEXT COMMENT '更新内容',
    images JSON COMMENT '图片数组',
    videos JSON COMMENT '视频数组',
    weight DECIMAL(5,2) COMMENT '体重记录',
    health_note TEXT COMMENT '健康备注',
    created_by ENUM('system', 'merchant', 'admin') DEFAULT 'merchant' COMMENT '创建者类型',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    FOREIGN KEY (animal_id) REFERENCES animals(id) ON DELETE CASCADE,
    FOREIGN KEY (claim_id) REFERENCES animal_claims(id) ON DELETE SET NULL,
    INDEX idx_animal_id (animal_id),
    INDEX idx_claim_id (claim_id),
    INDEX idx_update_type (update_type),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='动物更新记录表';
```

## 6. 数据库索引优化

### 6.1 主要索引策略

#### 用户表 (users) 索引
- 主键索引：`PRIMARY KEY (id)`
- 状态索引：`INDEX idx_status (status)` - 用于用户状态筛选
- 用户类型索引：`INDEX idx_user_type (user_type)` - 用于用户类型查询
- 等级索引：`INDEX idx_level (level)` - 用于用户等级排序
- 创建时间索引：`INDEX idx_created_at (created_at)` - 用于时间范围查询

#### 管理员表 (admins) 索引
- 主键索引：`PRIMARY KEY (id)`
- 唯一索引：`UNIQUE KEY (username)`, `UNIQUE KEY (email)`
- 角色索引：`INDEX idx_role (role)` - 用于权限管理
- 状态索引：`INDEX idx_status (status)` - 用于状态筛选

#### 商家表 (merchants) 索引
- 主键索引：`PRIMARY KEY (id)`
- 外键索引：`INDEX idx_user_id (user_id)` - 关联用户查询
- 状态索引：`INDEX idx_status (status)` - 商家状态筛选
- 评分索引：`INDEX idx_rating (rating)` - 评分排序
- 地理位置复合索引：`INDEX idx_location (latitude, longitude)` - 地理位置查询

#### 动物表 (animals) 索引
- 主键索引：`PRIMARY KEY (id)`
- 外键索引：`INDEX idx_farmer_id (farmer_id)` - 农场主查询
- 类型索引：`INDEX idx_type (type)` - 动物类型筛选
- 状态索引：`INDEX idx_status (status)` - 动物状态筛选
- 价格索引：`INDEX idx_price (price)` - 价格排序

#### 旅行计划表 (travel_plans) 索引
- 主键索引：`PRIMARY KEY (id)`
- 外键索引：`INDEX idx_created_by (created_by)` - 创建者查询
- 目的地索引：`INDEX idx_destination (destination)` - 目的地搜索
- 状态索引：`INDEX idx_status (status)` - 计划状态筛选
- 开始日期索引：`INDEX idx_start_date (start_date)` - 日期排序

#### 订单表 (orders) 索引
- 主键索引：`PRIMARY KEY (id)`
- 外键索引：`INDEX idx_user_id (user_id)` - 用户订单查询
- 订单号唯一索引：`UNIQUE KEY (order_number)` - 订单号查询
- 状态索引：`INDEX idx_status (status)` - 订单状态筛选
- 支付状态索引：`INDEX idx_payment_status (payment_status)` - 支付状态筛选

### 6.2 查询优化建议

1. **分页查询优化**：
   - 使用 `LIMIT` 和 `OFFSET` 进行分页
   - 对于大数据量分页，建议使用游标分页

2. **复合索引使用**：
   - 按照查询频率和选择性创建复合索引
   - 遵循最左前缀原则

3. **避免全表扫描**：
   - 在 WHERE 条件中使用索引字段
   - 避免在索引字段上使用函数

## 7. 数据库安全策略

### 7.1 访问控制
- 使用专用数据库用户，限制权限
- 定期更换数据库密码
- 启用SSL连接加密

### 7.2 数据加密
- 敏感字段（如密码）使用哈希加密
- 个人信息字段考虑加密存储
- 传输过程使用HTTPS协议

### 7.3 备份策略
- 每日自动备份数据库
- 定期测试备份恢复流程
- 异地备份保证数据安全

## 8. 性能监控与优化

### 8.1 监控指标
- 查询响应时间
- 数据库连接数
- 慢查询日志分析
- 索引使用率统计

### 8.2 优化策略
- 定期分析慢查询并优化
- 监控表大小，适时进行分区
- 定期更新表统计信息
- 合理设置数据库参数

## 9. 数据库维护

### 9.1 日常维护
- 定期检查数据库状态
- 清理过期的临时数据
- 监控磁盘空间使用
- 更新数据库统计信息

### 9.2 版本管理
- 使用数据库迁移脚本管理结构变更
- 记录每次结构变更的版本号
- 保持开发、测试、生产环境一致

## 10. 总结

本数据库设计文档基于解班客项目的实际需求，涵盖了用户管理、商家管理、动物认领、旅行计划、花卉产品、订单支付等核心业务模块。设计遵循了数据库设计的最佳实践，包括：

1. **规范化设计**：避免数据冗余，保证数据一致性
2. **性能优化**：合理设计索引，优化查询性能
3. **扩展性**：预留扩展空间，支持业务发展
4. **安全性**：实施访问控制和数据加密
5. **可维护性**：清晰的表结构和完善的文档

### 10.1 当前数据库统计
- **总表数**：14张表
- **核心业务表**：8张（users, admins, merchants, animals, animal_claims, travel_plans, travel_registrations, flowers, orders, payments, refunds）
- **辅助系统表**：3张（email_verifications, password_resets, login_attempts）
- **外键关系**：13个外键约束

### 10.2 后续优化方向
1. 根据业务发展需要，考虑添加缓存层
2. 对于高频查询表，考虑读写分离
3. 监控数据增长，适时进行分库分表
4. 完善数据备份和灾难恢复方案

---

**文档版本**：v2.0  
**最后更新**：2024年1月  
**维护人员**：开发团队  
**审核状态**：已审核

#### 5.2 订单表 (orders)
```sql
CREATE TABLE orders (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '订单ID',
    order_number VARCHAR(32) UNIQUE NOT NULL COMMENT '订单号',
    user_id INT NOT NULL COMMENT '用户ID',
    merchant_id INT NOT NULL COMMENT '商家ID',
    order_type ENUM('product', 'animal_claim', 'activity', 'service') NOT NULL COMMENT '订单类型',
    total_amount DECIMAL(10,2) NOT NULL COMMENT '订单总金额',
    discount_amount DECIMAL(10,2) DEFAULT 0.00 COMMENT '优惠金额',
    shipping_fee DECIMAL(10,2) DEFAULT 0.00 COMMENT '运费',
    final_amount DECIMAL(10,2) NOT NULL COMMENT '实付金额',
    payment_method ENUM('wechat', 'alipay', 'bank_card', 'points') COMMENT '支付方式',
    payment_status ENUM('pending', 'paid', 'failed', 'refunded', 'partial_refund') DEFAULT 'pending' COMMENT '支付状态',
    order_status ENUM('pending', 'confirmed', 'processing', 'shipped', 'delivered', 'completed', 'cancelled') DEFAULT 'pending' COMMENT '订单状态',
    delivery_info JSON COMMENT '配送信息',
    remark TEXT COMMENT '订单备注',
    cancel_reason TEXT COMMENT '取消原因',
    refund_reason TEXT COMMENT '退款原因',
    ordered_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '下单时间',
    paid_at TIMESTAMP COMMENT '支付时间',
    shipped_at TIMESTAMP COMMENT '发货时间',
    delivered_at TIMESTAMP COMMENT '收货时间',
    completed_at TIMESTAMP COMMENT '完成时间',
    cancelled_at TIMESTAMP COMMENT '取消时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (merchant_id) REFERENCES merchants(id) ON DELETE CASCADE,
    UNIQUE KEY uk_order_number (order_number),
    INDEX idx_user_id (user_id),
    INDEX idx_merchant_id (merchant_id),
    INDEX idx_order_type (order_type),
    INDEX idx_payment_status (payment_status),
    INDEX idx_order_status (order_status),
    INDEX idx_ordered_at (ordered_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单主表';
```

#### 5.3 订单明细表 (order_items)
```sql
CREATE TABLE order_items (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '订单明细ID',
    order_id INT NOT NULL COMMENT '订单ID',
    product_id INT COMMENT '商品ID',
    animal_id INT COMMENT '动物ID（动物认领订单）',
    activity_id INT COMMENT '活动ID（活动报名订单）',
    item_name VARCHAR(100) NOT NULL COMMENT '商品/服务名称',
    item_description TEXT COMMENT '商品/服务描述',
    unit_price DECIMAL(10,2) NOT NULL COMMENT '单价',
    quantity INT NOT NULL COMMENT '数量',
    total_price DECIMAL(10,2) NOT NULL COMMENT '小计金额',
    specifications JSON COMMENT '规格信息',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
    INDEX idx_order_id (order_id),
    INDEX idx_product_id (product_id),
    INDEX idx_animal_id (animal_id),
    INDEX idx_activity_id (activity_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单明细表';
```

### 6. 活动管理模块

#### 6.1 活动表 (activities)
```sql
CREATE TABLE activities (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '活动ID',
    merchant_id INT NOT NULL COMMENT '组织商家ID',
    title VARCHAR(100) NOT NULL COMMENT '活动标题',
    description TEXT COMMENT '活动描述',
    activity_type ENUM('travel', 'farm_visit', 'workshop', 'exhibition', 'social', 'other') NOT NULL COMMENT '活动类型',
    location VARCHAR(200) NOT NULL COMMENT '活动地点',
    address TEXT COMMENT '详细地址',
    latitude DECIMAL(10,8) COMMENT '纬度',
    longitude DECIMAL(11,8) COMMENT '经度',
    start_time DATETIME NOT NULL COMMENT '开始时间',
    end_time DATETIME NOT NULL COMMENT '结束时间',
    registration_start DATETIME COMMENT '报名开始时间',
    registration_end DATETIME COMMENT '报名结束时间',
    max_participants INT COMMENT '最大参与人数',
    current_participants INT DEFAULT 0 COMMENT '当前参与人数',
    min_participants INT DEFAULT 1 COMMENT '最少参与人数',
    price DECIMAL(10,2) DEFAULT 0.00 COMMENT '活动费用',
    age_min INT COMMENT '最小年龄限制',
    age_max INT COMMENT '最大年龄限制',
    gender_requirement ENUM('male', 'female', 'mixed', 'no_requirement') DEFAULT 'no_requirement' COMMENT '性别要求',
    requirements TEXT COMMENT '参与要求',
    includes TEXT COMMENT '费用包含',
    excludes TEXT COMMENT '费用不含',
    notes TEXT COMMENT '注意事项',
    images JSON COMMENT '活动图片',
    contact_info JSON COMMENT '联系方式',
    status ENUM('draft', 'published', 'full', 'ongoing', 'completed', 'cancelled') DEFAULT 'draft' COMMENT '活动状态',
    featured BOOLEAN DEFAULT FALSE COMMENT '是否推荐',
    view_count INT DEFAULT 0 COMMENT '浏览次数',
    like_count INT DEFAULT 0 COMMENT '点赞次数',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    FOREIGN KEY (merchant_id) REFERENCES merchants(id) ON DELETE CASCADE,
    INDEX idx_merchant_id (merchant_id),
    INDEX idx_activity_type (activity_type),
    INDEX idx_location (location),
    INDEX idx_start_time (start_time),
    INDEX idx_status (status),
    INDEX idx_featured (featured)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='活动信息表';
```

### 7. 系统管理模块

#### 7.1 管理员表 (admins)
```sql
CREATE TABLE admins (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '管理员ID',
    username VARCHAR(50) UNIQUE NOT NULL COMMENT '用户名',
    password VARCHAR(255) NOT NULL COMMENT '密码哈希',
    email VARCHAR(100) UNIQUE NOT NULL COMMENT '邮箱',
    nickname VARCHAR(50) COMMENT '昵称',
    avatar VARCHAR(255) COMMENT '头像',
    role ENUM('super_admin', 'admin', 'moderator', 'customer_service') NOT NULL COMMENT '角色',
    permissions JSON COMMENT '权限列表',
    status ENUM('active', 'inactive', 'locked') DEFAULT 'active' COMMENT '状态',
    last_login_at TIMESTAMP COMMENT '最后登录时间',
    last_login_ip VARCHAR(45) COMMENT '最后登录IP',
    login_count INT DEFAULT 0 COMMENT '登录次数',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    UNIQUE KEY uk_username (username),
    UNIQUE KEY uk_email (email),
    INDEX idx_role (role),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='管理员表';
```

#### 7.2 系统配置表 (system_configs)
```sql
CREATE TABLE system_configs (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '配置ID',
    config_key VARCHAR(100) UNIQUE NOT NULL COMMENT '配置键',
    config_value TEXT COMMENT '配置值',
    config_type ENUM('string', 'number', 'boolean', 'json', 'text') DEFAULT 'string' COMMENT '配置类型',
    description TEXT COMMENT '配置描述',
    category VARCHAR(50) COMMENT '配置分类',
    is_public BOOLEAN DEFAULT FALSE COMMENT '是否公开',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    UNIQUE KEY uk_config_key (config_key),
    INDEX idx_category (category),
    INDEX idx_is_public (is_public)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置表';
```

## 🔍 索引优化策略

### 主键索引
所有表都使用自增整型主键，确保插入性能和唯一性。

### 唯一索引
- `users.openid` - 微信用户唯一标识
- `users.phone` - 用户手机号
- `merchants.business_license` - 商家营业执照号
- `orders.order_number` - 订单号

### 复合索引
```sql
-- 旅行计划查询优化
ALTER TABLE travel_plans ADD INDEX idx_destination_date (destination, start_date, status);

-- 动物搜索优化
ALTER TABLE animals ADD INDEX idx_type_status_price (type, status, price);

-- 订单查询优化
ALTER TABLE orders ADD INDEX idx_user_status_time (user_id, order_status, created_at);
```

### 覆盖索引
```sql
-- 用户列表查询覆盖索引
ALTER TABLE users ADD INDEX idx_status_created_cover (status, created_at, id, nickname, avatar);

-- 商品列表查询覆盖索引
ALTER TABLE products ADD INDEX idx_merchant_status_cover (merchant_id, status, id, name, price, images);
```

## 🔄 数据库维护

### 分区策略

#### 按时间分区（订单表）
```sql
-- 按月分区订单表
ALTER TABLE orders PARTITION BY RANGE (YEAR(created_at) * 100 + MONTH(created_at)) (
    PARTITION p202501 VALUES LESS THAN (202502),
    PARTITION p202502 VALUES LESS THAN (202503),
    PARTITION p202503 VALUES LESS THAN (202504),
    -- ... 更多分区
    PARTITION p_future VALUES LESS THAN MAXVALUE
);
```

### 数据归档策略

#### 日志表归档
```sql
-- 创建归档表
CREATE TABLE admin_logs_archive LIKE admin_logs;

-- 归档6个月前的日志
INSERT INTO admin_logs_archive 
SELECT * FROM admin_logs 
WHERE created_at < DATE_SUB(NOW(), INTERVAL 6 MONTH);

-- 删除已归档的数据
DELETE FROM admin_logs 
WHERE created_at < DATE_SUB(NOW(), INTERVAL 6 MONTH);
```

### 备份策略

#### 全量备份脚本
```bash
#!/bin/bash
# 数据库全量备份脚本

BACKUP_DIR="/opt/backups/mysql"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME="jiebandata"

# 创建备份目录
mkdir -p $BACKUP_DIR

# 执行备份
mysqldump -h localhost -u backup_user -p$BACKUP_PASSWORD \
  --single-transaction \
  --routines \
  --triggers \
  --events \
  $DB_NAME > $BACKUP_DIR/jiebandata_$DATE.sql

# 压缩备份文件
gzip $BACKUP_DIR/jiebandata_$DATE.sql

# 删除7天前的备份
find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete

echo "数据库备份完成: jiebandata_$DATE.sql.gz"
```

## 📊 性能监控

### 慢查询监控
```sql
-- 开启慢查询日志
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
SET GLOBAL log_queries_not_using_indexes = 'ON';
```

### 表空间监控
```sql
-- 查看表大小
SELECT 
    table_name,
    ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size (MB)'
FROM information_schema.tables 
WHERE table_schema = 'jiebandata'
ORDER BY (data_length + index_length) DESC;
```

### 索引使用情况
```sql
-- 查看未使用的索引
SELECT 
    t.table_schema,
    t.table_name,
    s.index_name,
    s.cardinality
FROM information_schema.tables t
LEFT JOIN information_schema.statistics s ON t.table_name = s.table_name
WHERE t.table_schema = 'jbkdata'
AND s.index_name IS NOT NULL
AND s.index_name != 'PRIMARY';
```

## 12. 数据库连接和维护

### 12.1 连接管理
```javascript
// 数据库连接池配置
const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: 'nj-cdb-3pwh2kz1.sql.tencentcdb.com',
  port: 20784,
  user: 'jiebanke',
  password: 'aiot741$12346',
  database: 'jbkdata',
  connectionLimit: 10,
  charset: 'utf8mb4',
  timezone: '+08:00',
  acquireTimeout: 60000,
  timeout: 60000,
  reconnect: true
});

module.exports = pool;
```

### 12.2 数据库维护脚本
```bash
#!/bin/bash
# 数据库备份脚本
DB_HOST="nj-cdb-3pwh2kz1.sql.tencentcdb.com"
DB_PORT="20784"
DB_USER="jiebanke"
DB_PASSWORD="aiot741$12346"
DB_NAME="jbkdata"

# 创建备份
mysqldump -h$DB_HOST -P$DB_PORT -u$DB_USER -p$DB_PASSWORD $DB_NAME > backup_$(date +%Y%m%d_%H%M%S).sql

echo "数据库备份完成"
```

### 12.3 监控和告警
- **连接数监控**：监控当前连接数，避免超过连接池限制
- **慢查询监控**：监控执行时间超过2秒的查询
- **磁盘空间监控**：监控数据库磁盘使用情况
- **性能指标监控**：QPS、TPS、响应时间等关键指标

---

*文档版本：v2.0*  
*最后更新：2025年1月*  
*数据库实例：腾讯云MySQL - jbkdata*