# 🗄️ 结伴客数据库设计文档

## 📋 数据库概述

结伴客系统采用MySQL 8.0作为主要数据存储，设计了完整的数据库架构来支持结伴旅行、动物认领、商家服务等核心业务功能。数据库设计遵循第三范式，确保数据一致性和完整性。

## 🔧 数据库配置

### 环境配置

#### 开发环境
- **主机**：localhost
- **端口**：3306
- **数据库名**：jiebandata_dev
- **字符集**：utf8mb4
- **排序规则**：utf8mb4_unicode_ci

#### 测试环境
- **主机**：192.168.0.240
- **端口**：3306
- **用户名**：root
- **密码**：aiot$Aiot123
- **数据库名**：jiebandata_test

#### 生产环境
- **主机**：129.211.213.226
- **端口**：9527
- **用户名**：root
- **密码**：aiotAiot123!
- **数据库名**：jiebandata

### 数据库架构

#### 主从复制架构
```mermaid
graph LR
    A[应用服务器] --> B[MySQL主库<br/>写操作]
    B --> C[MySQL从库1<br/>读操作]
    B --> D[MySQL从库2<br/>读操作]
    A --> C
    A --> D
    
    E[备份服务器] --> B
    F[监控系统] --> B
    F --> C
    F --> D
```

## 📊 数据库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',
    openid VARCHAR(100) UNIQUE NOT NULL COMMENT '微信openid',
    unionid VARCHAR(100) COMMENT '微信unionid',
    nickname VARCHAR(50) NOT NULL COMMENT '用户昵称',
    avatar VARCHAR(255) COMMENT '头像URL',
    gender ENUM('male', 'female', 'unknown') DEFAULT 'unknown' COMMENT '性别',
    birthday DATE COMMENT '生日',
    phone VARCHAR(20) UNIQUE COMMENT '手机号码',
    email VARCHAR(100) UNIQUE COMMENT '邮箱地址',
    province VARCHAR(50) COMMENT '省份',
    city VARCHAR(50) COMMENT '城市',
    travel_count INT DEFAULT 0 COMMENT '旅行次数',
    animal_claim_count INT DEFAULT 0 COMMENT '认领动物数量',
    points INT DEFAULT 0 COMMENT '积分',
    level ENUM('bronze', 'silver', 'gold', 'platinum') DEFAULT 'bronze' COMMENT '用户等级',
    status ENUM('active', 'inactive', 'banned') DEFAULT 'active' COMMENT '用户状态',
    last_login_at TIMESTAMP COMMENT '最后登录时间',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    
    INDEX idx_openid (openid),
    INDEX idx_phone (phone),
    INDEX idx_email (email),
    INDEX idx_status (status),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户基础信息表';
```

#### 1.2 用户兴趣表 (user_interests)
```sql
CREATE TABLE user_interests (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '兴趣ID',
    user_id INT NOT NULL COMMENT '用户ID',
    interest_name VARCHAR(50) NOT NULL COMMENT '兴趣名称',
    interest_type ENUM('travel', 'food', 'sports', 'culture', 'nature') COMMENT '兴趣类型',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    UNIQUE KEY uk_user_interest (user_id, interest_name),
    INDEX idx_user_id (user_id),
    INDEX idx_interest_type (interest_type)
) 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',
    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='动物更新记录表';
```

### 5. 商品订单模块

#### 5.1 商品表 (products)
```sql
CREATE TABLE products (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '商品ID',
    merchant_id INT NOT NULL COMMENT '商家ID',
    category_id INT COMMENT '分类ID',
    name VARCHAR(100) NOT NULL COMMENT '商品名称',
    description TEXT COMMENT '商品描述',
    price DECIMAL(10,2) NOT NULL COMMENT '商品价格',
    original_price DECIMAL(10,2) COMMENT '原价',
    stock INT DEFAULT 0 COMMENT '库存数量',
    min_order_quantity INT DEFAULT 1 COMMENT '最小起订量',
    max_order_quantity INT COMMENT '最大订购量',
    images JSON COMMENT '商品图片数组',
    specifications JSON COMMENT '商品规格',
    tags VARCHAR(255) COMMENT '商品标签',
    weight DECIMAL(8,3) COMMENT '商品重量（公斤）',
    dimensions VARCHAR(50) COMMENT '商品尺寸',
    shelf_life INT COMMENT '保质期（天）',
    storage_conditions TEXT COMMENT '储存条件',
    delivery_info TEXT COMMENT '配送信息',
    rating DECIMAL(3,2) DEFAULT 5.00 COMMENT '商品评分',
    review_count INT DEFAULT 0 COMMENT '评价数量',
    sales_count INT DEFAULT 0 COMMENT '销售数量',
    status ENUM('active', 'inactive', 'out_of_stock', 'discontinued') DEFAULT 'active' COMMENT '商品状态',
    sort_order 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_category_id (category_id),
    INDEX idx_price (price),
    INDEX idx_status (status),
    INDEX idx_rating (rating),
    INDEX idx_sales_count (sales_count)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='商品信息表';
```

#### 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 = 'jiebandata'
AND s.index_name IS NOT NULL
AND s.index_name != 'PRIMARY';
```

---

*文档版本：v1.0*  
*最后更新：2025年1月*