# 数据库设计文档

## 版本历史
| 版本 | 日期 | 作者 | 变更说明 |
|------|------|------|----------|
| 1.0 | 2024-01-20 | 后端团队 | 初始版本 |

## 1. 数据库概述

### 1.1 设计原则
- **规范化**: 遵循数据库范式，减少数据冗余
- **性能优化**: 合理设计索引，优化查询性能
- **扩展性**: 支持水平和垂直扩展
- **一致性**: 保证数据的完整性和一致性
- **安全性**: 敏感数据加密存储
- **可维护性**: 清晰的表结构和命名规范

### 1.2 技术选型
- **主数据库**: MySQL 8.0
- **缓存数据库**: Redis 7.0
- **文档数据库**: MongoDB 6.0 (用于日志和非结构化数据)
- **搜索引擎**: Elasticsearch 8.0 (用于全文搜索)

### 1.3 数据库架构
```
┌─────────────────────────────────────────────────────────────┐
│                    应用层 (Application)                      │
├─────────────────────────────────────────────────────────────┤
│                    缓存层 (Redis)                           │
├─────────────────────────────────────────────────────────────┤
│                 主数据库 (MySQL Master)                      │
├─────────────────────────────────────────────────────────────┤
│                 从数据库 (MySQL Slaves)                      │
├─────────────────────────────────────────────────────────────┤
│              文档数据库 (MongoDB) | 搜索引擎 (ES)             │
└─────────────────────────────────────────────────────────────┘
```

## 2. MySQL数据库设计

### 2.1 数据库命名规范
- **数据库名**: 使用小写字母和下划线，如 `xlxumu_main`
- **表名**: 使用小写字母和下划线，复数形式，如 `users`, `farm_animals`
- **字段名**: 使用小写字母和下划线，如 `user_id`, `created_at`
- **索引名**: 使用 `idx_` 前缀，如 `idx_users_phone`
- **外键名**: 使用 `fk_` 前缀，如 `fk_orders_user_id`

### 2.2 核心表结构

#### 2.2.1 用户相关表

**用户表 (users)**
```sql
CREATE TABLE `users` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `phone` varchar(20) NOT NULL COMMENT '手机号',
  `email` varchar(100) DEFAULT NULL COMMENT '邮箱',
  `password_hash` varchar(255) NOT NULL COMMENT '密码哈希',
  `salt` varchar(32) NOT NULL COMMENT '密码盐值',
  `avatar` varchar(255) DEFAULT NULL COMMENT '头像URL',
  `real_name` varchar(50) DEFAULT NULL COMMENT '真实姓名',
  `id_card` varchar(18) DEFAULT NULL COMMENT '身份证号',
  `gender` tinyint(1) DEFAULT NULL COMMENT '性别：1-男，2-女',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `address` varchar(255) DEFAULT NULL COMMENT '地址',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-禁用，1-正常',
  `last_login_at` timestamp NULL DEFAULT NULL COMMENT '最后登录时间',
  `last_login_ip` varchar(45) DEFAULT NULL COMMENT '最后登录IP',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted_at` timestamp NULL DEFAULT NULL COMMENT '删除时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_users_username` (`username`),
  UNIQUE KEY `uk_users_phone` (`phone`),
  UNIQUE KEY `uk_users_email` (`email`),
  KEY `idx_users_status` (`status`),
  KEY `idx_users_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';
```

**用户认证表 (user_auths)**
```sql
CREATE TABLE `user_auths` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
  `auth_type` varchar(20) NOT NULL COMMENT '认证类型：password,wechat,qq,alipay',
  `auth_key` varchar(100) NOT NULL COMMENT '认证标识',
  `auth_secret` varchar(255) DEFAULT NULL COMMENT '认证密钥',
  `expires_at` timestamp NULL DEFAULT NULL COMMENT '过期时间',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_auths_type_key` (`auth_type`, `auth_key`),
  KEY `fk_user_auths_user_id` (`user_id`),
  CONSTRAINT `fk_user_auths_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户认证表';
```

**用户角色表 (user_roles)**
```sql
CREATE TABLE `user_roles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
  `role_id` bigint(20) unsigned NOT NULL COMMENT '角色ID',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_user_roles_user_role` (`user_id`, `role_id`),
  KEY `fk_user_roles_role_id` (`role_id`),
  CONSTRAINT `fk_user_roles_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_user_roles_role_id` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户角色关联表';
```

#### 2.2.2 权限相关表

**角色表 (roles)**
```sql
CREATE TABLE `roles` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '角色ID',
  `name` varchar(50) NOT NULL COMMENT '角色名称',
  `code` varchar(50) NOT NULL COMMENT '角色编码',
  `description` varchar(255) DEFAULT NULL COMMENT '角色描述',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-禁用，1-正常',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_roles_code` (`code`),
  KEY `idx_roles_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色表';
```

**权限表 (permissions)**
```sql
CREATE TABLE `permissions` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '权限ID',
  `name` varchar(50) NOT NULL COMMENT '权限名称',
  `code` varchar(100) NOT NULL COMMENT '权限编码',
  `type` varchar(20) NOT NULL COMMENT '权限类型：menu,button,api',
  `parent_id` bigint(20) unsigned DEFAULT NULL COMMENT '父权限ID',
  `path` varchar(255) DEFAULT NULL COMMENT '路径',
  `icon` varchar(50) DEFAULT NULL COMMENT '图标',
  `sort_order` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-禁用，1-正常',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_permissions_code` (`code`),
  KEY `idx_permissions_parent_id` (`parent_id`),
  KEY `idx_permissions_type` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='权限表';
```

**角色权限表 (role_permissions)**
```sql
CREATE TABLE `role_permissions` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `role_id` bigint(20) unsigned NOT NULL COMMENT '角色ID',
  `permission_id` bigint(20) unsigned NOT NULL COMMENT '权限ID',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_role_permissions_role_permission` (`role_id`, `permission_id`),
  KEY `fk_role_permissions_permission_id` (`permission_id`),
  CONSTRAINT `fk_role_permissions_role_id` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_role_permissions_permission_id` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色权限关联表';
```

#### 2.2.3 养殖相关表

**养殖场表 (farms)**
```sql
CREATE TABLE `farms` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '养殖场ID',
  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
  `name` varchar(100) NOT NULL COMMENT '养殖场名称',
  `code` varchar(50) NOT NULL COMMENT '养殖场编码',
  `type` varchar(20) NOT NULL COMMENT '养殖类型：pig,cattle,sheep,chicken,fish',
  `area` decimal(10,2) DEFAULT NULL COMMENT '养殖面积(平方米)',
  `capacity` int(11) DEFAULT NULL COMMENT '养殖容量',
  `address` varchar(255) NOT NULL COMMENT '详细地址',
  `province` varchar(50) NOT NULL COMMENT '省份',
  `city` varchar(50) NOT NULL COMMENT '城市',
  `district` varchar(50) NOT NULL COMMENT '区县',
  `longitude` decimal(10,7) DEFAULT NULL COMMENT '经度',
  `latitude` decimal(10,7) DEFAULT NULL COMMENT '纬度',
  `license_number` varchar(100) DEFAULT NULL COMMENT '许可证号',
  `license_image` varchar(255) DEFAULT NULL COMMENT '许可证图片',
  `description` text COMMENT '养殖场描述',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-停用，1-正常，2-审核中',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted_at` timestamp NULL DEFAULT NULL COMMENT '删除时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_farms_code` (`code`),
  KEY `fk_farms_user_id` (`user_id`),
  KEY `idx_farms_type` (`type`),
  KEY `idx_farms_status` (`status`),
  KEY `idx_farms_location` (`province`, `city`, `district`),
  CONSTRAINT `fk_farms_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='养殖场表';
```

**动物表 (animals)**
```sql
CREATE TABLE `animals` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '动物ID',
  `farm_id` bigint(20) unsigned NOT NULL COMMENT '养殖场ID',
  `category_id` bigint(20) unsigned NOT NULL COMMENT '动物分类ID',
  `code` varchar(50) NOT NULL COMMENT '动物编号',
  `name` varchar(100) DEFAULT NULL COMMENT '动物名称',
  `breed` varchar(50) DEFAULT NULL COMMENT '品种',
  `gender` tinyint(1) DEFAULT NULL COMMENT '性别：1-雄性，2-雌性',
  `birth_date` date DEFAULT NULL COMMENT '出生日期',
  `weight` decimal(8,2) DEFAULT NULL COMMENT '体重(kg)',
  `health_status` varchar(20) NOT NULL DEFAULT 'healthy' COMMENT '健康状态：healthy,sick,dead',
  `parent_male_id` bigint(20) unsigned DEFAULT NULL COMMENT '父亲ID',
  `parent_female_id` bigint(20) unsigned DEFAULT NULL COMMENT '母亲ID',
  `purchase_price` decimal(10,2) DEFAULT NULL COMMENT '购买价格',
  `purchase_date` date DEFAULT NULL COMMENT '购买日期',
  `source` varchar(100) DEFAULT NULL COMMENT '来源',
  `notes` text COMMENT '备注',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-已出售，1-在养，2-死亡',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted_at` timestamp NULL DEFAULT NULL COMMENT '删除时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_animals_code` (`code`),
  KEY `fk_animals_farm_id` (`farm_id`),
  KEY `fk_animals_category_id` (`category_id`),
  KEY `idx_animals_status` (`status`),
  KEY `idx_animals_health_status` (`health_status`),
  KEY `idx_animals_birth_date` (`birth_date`),
  CONSTRAINT `fk_animals_farm_id` FOREIGN KEY (`farm_id`) REFERENCES `farms` (`id`),
  CONSTRAINT `fk_animals_category_id` FOREIGN KEY (`category_id`) REFERENCES `animal_categories` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='动物表';
```

**动物分类表 (animal_categories)**
```sql
CREATE TABLE `animal_categories` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '分类ID',
  `name` varchar(50) NOT NULL COMMENT '分类名称',
  `code` varchar(20) NOT NULL COMMENT '分类编码',
  `parent_id` bigint(20) unsigned DEFAULT NULL COMMENT '父分类ID',
  `description` varchar(255) DEFAULT NULL COMMENT '分类描述',
  `sort_order` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-禁用，1-正常',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_animal_categories_code` (`code`),
  KEY `idx_animal_categories_parent_id` (`parent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='动物分类表';
```

#### 2.2.4 健康管理表

**健康记录表 (health_records)**
```sql
CREATE TABLE `health_records` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '记录ID',
  `animal_id` bigint(20) unsigned NOT NULL COMMENT '动物ID',
  `record_type` varchar(20) NOT NULL COMMENT '记录类型：checkup,vaccination,treatment,death',
  `record_date` date NOT NULL COMMENT '记录日期',
  `symptoms` text COMMENT '症状描述',
  `diagnosis` text COMMENT '诊断结果',
  `treatment` text COMMENT '治疗方案',
  `medicine` varchar(255) DEFAULT NULL COMMENT '用药',
  `dosage` varchar(100) DEFAULT NULL COMMENT '用药剂量',
  `veterinarian` varchar(50) DEFAULT NULL COMMENT '兽医',
  `cost` decimal(10,2) DEFAULT NULL COMMENT '费用',
  `next_checkup_date` date DEFAULT NULL COMMENT '下次检查日期',
  `notes` text COMMENT '备注',
  `images` json DEFAULT NULL COMMENT '相关图片',
  `created_by` bigint(20) unsigned NOT NULL COMMENT '创建人',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `fk_health_records_animal_id` (`animal_id`),
  KEY `idx_health_records_type` (`record_type`),
  KEY `idx_health_records_date` (`record_date`),
  CONSTRAINT `fk_health_records_animal_id` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='健康记录表';
```

**疫苗接种表 (vaccinations)**
```sql
CREATE TABLE `vaccinations` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '接种ID',
  `animal_id` bigint(20) unsigned NOT NULL COMMENT '动物ID',
  `vaccine_name` varchar(100) NOT NULL COMMENT '疫苗名称',
  `vaccine_type` varchar(50) NOT NULL COMMENT '疫苗类型',
  `batch_number` varchar(50) DEFAULT NULL COMMENT '批次号',
  `manufacturer` varchar(100) DEFAULT NULL COMMENT '生产厂家',
  `vaccination_date` date NOT NULL COMMENT '接种日期',
  `next_vaccination_date` date DEFAULT NULL COMMENT '下次接种日期',
  `dosage` varchar(50) DEFAULT NULL COMMENT '接种剂量',
  `method` varchar(50) DEFAULT NULL COMMENT '接种方式',
  `veterinarian` varchar(50) DEFAULT NULL COMMENT '接种兽医',
  `cost` decimal(10,2) DEFAULT NULL COMMENT '费用',
  `side_effects` text COMMENT '副作用',
  `notes` text COMMENT '备注',
  `created_by` bigint(20) unsigned NOT NULL COMMENT '创建人',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `fk_vaccinations_animal_id` (`animal_id`),
  KEY `idx_vaccinations_date` (`vaccination_date`),
  KEY `idx_vaccinations_next_date` (`next_vaccination_date`),
  CONSTRAINT `fk_vaccinations_animal_id` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='疫苗接种表';
```

#### 2.2.5 饲养管理表

**饲料表 (feeds)**
```sql
CREATE TABLE `feeds` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '饲料ID',
  `name` varchar(100) NOT NULL COMMENT '饲料名称',
  `code` varchar(50) NOT NULL COMMENT '饲料编码',
  `type` varchar(20) NOT NULL COMMENT '饲料类型：concentrate,roughage,additive',
  `brand` varchar(50) DEFAULT NULL COMMENT '品牌',
  `specification` varchar(100) DEFAULT NULL COMMENT '规格',
  `unit` varchar(10) NOT NULL COMMENT '单位：kg,ton,bag',
  `protein_content` decimal(5,2) DEFAULT NULL COMMENT '蛋白质含量(%)',
  `fat_content` decimal(5,2) DEFAULT NULL COMMENT '脂肪含量(%)',
  `fiber_content` decimal(5,2) DEFAULT NULL COMMENT '纤维含量(%)',
  `moisture_content` decimal(5,2) DEFAULT NULL COMMENT '水分含量(%)',
  `energy_value` decimal(8,2) DEFAULT NULL COMMENT '能量值(MJ/kg)',
  `shelf_life` int(11) DEFAULT NULL COMMENT '保质期(天)',
  `storage_conditions` varchar(255) DEFAULT NULL COMMENT '储存条件',
  `description` text COMMENT '饲料描述',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态：0-停用，1-正常',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_feeds_code` (`code`),
  KEY `idx_feeds_type` (`type`),
  KEY `idx_feeds_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='饲料表';
```

**饲养记录表 (feeding_records)**
```sql
CREATE TABLE `feeding_records` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '记录ID',
  `farm_id` bigint(20) unsigned NOT NULL COMMENT '养殖场ID',
  `animal_id` bigint(20) unsigned DEFAULT NULL COMMENT '动物ID(可为空，表示批量饲养)',
  `feed_id` bigint(20) unsigned NOT NULL COMMENT '饲料ID',
  `feeding_date` date NOT NULL COMMENT '饲养日期',
  `feeding_time` time NOT NULL COMMENT '饲养时间',
  `quantity` decimal(10,2) NOT NULL COMMENT '饲料数量',
  `unit` varchar(10) NOT NULL COMMENT '单位',
  `cost` decimal(10,2) DEFAULT NULL COMMENT '费用',
  `weather` varchar(20) DEFAULT NULL COMMENT '天气',
  `temperature` decimal(4,1) DEFAULT NULL COMMENT '温度(℃)',
  `humidity` decimal(5,2) DEFAULT NULL COMMENT '湿度(%)',
  `notes` text COMMENT '备注',
  `created_by` bigint(20) unsigned NOT NULL COMMENT '创建人',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `fk_feeding_records_farm_id` (`farm_id`),
  KEY `fk_feeding_records_animal_id` (`animal_id`),
  KEY `fk_feeding_records_feed_id` (`feed_id`),
  KEY `idx_feeding_records_date` (`feeding_date`),
  CONSTRAINT `fk_feeding_records_farm_id` FOREIGN KEY (`farm_id`) REFERENCES `farms` (`id`),
  CONSTRAINT `fk_feeding_records_animal_id` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`id`),
  CONSTRAINT `fk_feeding_records_feed_id` FOREIGN KEY (`feed_id`) REFERENCES `feeds` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='饲养记录表';
```

#### 2.2.6 交易相关表

**订单表 (orders)**
```sql
CREATE TABLE `orders` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '订单ID',
  `order_no` varchar(32) NOT NULL COMMENT '订单号',
  `buyer_id` bigint(20) unsigned NOT NULL COMMENT '买家ID',
  `seller_id` bigint(20) unsigned NOT NULL COMMENT '卖家ID',
  `farm_id` bigint(20) unsigned NOT NULL COMMENT '养殖场ID',
  `order_type` varchar(20) NOT NULL COMMENT '订单类型：animal,product,service',
  `total_amount` decimal(12,2) NOT NULL COMMENT '订单总金额',
  `discount_amount` decimal(12,2) NOT NULL DEFAULT '0.00' COMMENT '优惠金额',
  `shipping_fee` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '运费',
  `actual_amount` decimal(12,2) NOT NULL COMMENT '实付金额',
  `payment_method` varchar(20) DEFAULT NULL COMMENT '支付方式：alipay,wechat,bank',
  `payment_status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT '支付状态：pending,paid,failed,refunded',
  `order_status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT '订单状态：pending,confirmed,shipped,delivered,completed,cancelled',
  `shipping_address` json DEFAULT NULL COMMENT '收货地址',
  `shipping_method` varchar(20) DEFAULT NULL COMMENT '配送方式：express,pickup,delivery',
  `tracking_number` varchar(50) DEFAULT NULL COMMENT '物流单号',
  `notes` text COMMENT '订单备注',
  `paid_at` timestamp NULL DEFAULT NULL COMMENT '支付时间',
  `shipped_at` timestamp NULL DEFAULT NULL COMMENT '发货时间',
  `delivered_at` timestamp NULL DEFAULT NULL COMMENT '收货时间',
  `completed_at` timestamp NULL DEFAULT NULL COMMENT '完成时间',
  `cancelled_at` timestamp NULL DEFAULT NULL COMMENT '取消时间',
  `cancel_reason` varchar(255) DEFAULT NULL COMMENT '取消原因',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_orders_order_no` (`order_no`),
  KEY `fk_orders_buyer_id` (`buyer_id`),
  KEY `fk_orders_seller_id` (`seller_id`),
  KEY `fk_orders_farm_id` (`farm_id`),
  KEY `idx_orders_status` (`order_status`),
  KEY `idx_orders_payment_status` (`payment_status`),
  KEY `idx_orders_created_at` (`created_at`),
  CONSTRAINT `fk_orders_buyer_id` FOREIGN KEY (`buyer_id`) REFERENCES `users` (`id`),
  CONSTRAINT `fk_orders_seller_id` FOREIGN KEY (`seller_id`) REFERENCES `users` (`id`),
  CONSTRAINT `fk_orders_farm_id` FOREIGN KEY (`farm_id`) REFERENCES `farms` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单表';
```

**订单明细表 (order_items)**
```sql
CREATE TABLE `order_items` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '明细ID',
  `order_id` bigint(20) unsigned NOT NULL COMMENT '订单ID',
  `item_type` varchar(20) NOT NULL COMMENT '商品类型：animal,product,service',
  `item_id` bigint(20) unsigned NOT NULL COMMENT '商品ID',
  `item_name` varchar(255) NOT NULL COMMENT '商品名称',
  `item_code` varchar(50) DEFAULT NULL COMMENT '商品编码',
  `item_spec` varchar(255) DEFAULT NULL COMMENT '商品规格',
  `unit_price` decimal(10,2) NOT NULL COMMENT '单价',
  `quantity` decimal(10,2) NOT NULL COMMENT '数量',
  `unit` varchar(10) NOT NULL COMMENT '单位',
  `subtotal` decimal(12,2) NOT NULL COMMENT '小计',
  `notes` text COMMENT '备注',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `fk_order_items_order_id` (`order_id`),
  KEY `idx_order_items_item` (`item_type`, `item_id`),
  CONSTRAINT `fk_order_items_order_id` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单明细表';
```

#### 2.2.7 财务相关表

**财务记录表 (financial_records)**
```sql
CREATE TABLE `financial_records` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '记录ID',
  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户ID',
  `farm_id` bigint(20) unsigned DEFAULT NULL COMMENT '养殖场ID',
  `record_type` varchar(20) NOT NULL COMMENT '记录类型：income,expense',
  `category` varchar(50) NOT NULL COMMENT '分类：feed,medicine,equipment,labor,sale,other',
  `amount` decimal(12,2) NOT NULL COMMENT '金额',
  `description` varchar(255) NOT NULL COMMENT '描述',
  `related_id` bigint(20) unsigned DEFAULT NULL COMMENT '关联ID(订单ID等)',
  `related_type` varchar(20) DEFAULT NULL COMMENT '关联类型：order,purchase,salary',
  `payment_method` varchar(20) DEFAULT NULL COMMENT '支付方式',
  `receipt_image` varchar(255) DEFAULT NULL COMMENT '凭证图片',
  `record_date` date NOT NULL COMMENT '记录日期',
  `notes` text COMMENT '备注',
  `created_by` bigint(20) unsigned NOT NULL COMMENT '创建人',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `fk_financial_records_user_id` (`user_id`),
  KEY `fk_financial_records_farm_id` (`farm_id`),
  KEY `idx_financial_records_type` (`record_type`),
  KEY `idx_financial_records_category` (`category`),
  KEY `idx_financial_records_date` (`record_date`),
  CONSTRAINT `fk_financial_records_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
  CONSTRAINT `fk_financial_records_farm_id` FOREIGN KEY (`farm_id`) REFERENCES `farms` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='财务记录表';
```

#### 2.2.8 系统相关表

**系统配置表 (system_configs)**
```sql
CREATE TABLE `system_configs` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '配置ID',
  `config_key` varchar(100) NOT NULL COMMENT '配置键',
  `config_value` text NOT NULL COMMENT '配置值',
  `config_type` varchar(20) NOT NULL DEFAULT 'string' COMMENT '配置类型：string,number,boolean,json',
  `description` varchar(255) DEFAULT NULL COMMENT '配置描述',
  `is_public` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否公开：0-否，1-是',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_system_configs_key` (`config_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置表';
```

**操作日志表 (operation_logs)**
```sql
CREATE TABLE `operation_logs` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '日志ID',
  `user_id` bigint(20) unsigned DEFAULT NULL COMMENT '用户ID',
  `module` varchar(50) NOT NULL COMMENT '模块',
  `action` varchar(50) NOT NULL COMMENT '操作',
  `method` varchar(10) NOT NULL COMMENT '请求方法',
  `url` varchar(255) NOT NULL COMMENT '请求URL',
  `ip` varchar(45) NOT NULL COMMENT 'IP地址',
  `user_agent` varchar(500) DEFAULT NULL COMMENT '用户代理',
  `request_data` json DEFAULT NULL COMMENT '请求数据',
  `response_data` json DEFAULT NULL COMMENT '响应数据',
  `status_code` int(11) NOT NULL COMMENT '状态码',
  `execution_time` int(11) NOT NULL COMMENT '执行时间(ms)',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `idx_operation_logs_user_id` (`user_id`),
  KEY `idx_operation_logs_module` (`module`),
  KEY `idx_operation_logs_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';
```

### 2.3 索引设计

#### 2.3.1 主键索引
所有表都使用自增的 `bigint` 类型作为主键，确保唯一性和性能。

#### 2.3.2 唯一索引
- 用户表：用户名、手机号、邮箱
- 养殖场表：养殖场编码
- 动物表：动物编号
- 订单表：订单号

#### 2.3.3 普通索引
- 状态字段：便于按状态查询
- 时间字段：便于按时间范围查询
- 外键字段：提高关联查询性能
- 分类字段：便于分类统计

#### 2.3.4 复合索引
```sql
-- 用户角色复合索引
CREATE INDEX idx_user_roles_user_role ON user_roles (user_id, role_id);

-- 订单状态和时间复合索引
CREATE INDEX idx_orders_status_time ON orders (order_status, created_at);

-- 动物养殖场和状态复合索引
CREATE INDEX idx_animals_farm_status ON animals (farm_id, status);

-- 财务记录类型和日期复合索引
CREATE INDEX idx_financial_type_date ON financial_records (record_type, record_date);
```

### 2.4 分区设计

对于数据量较大的表，采用分区策略：

#### 2.4.1 按时间分区
```sql
-- 操作日志表按月分区
ALTER TABLE operation_logs PARTITION BY RANGE (YEAR(created_at) * 100 + MONTH(created_at)) (
    PARTITION p202401 VALUES LESS THAN (202402),
    PARTITION p202402 VALUES LESS THAN (202403),
    PARTITION p202403 VALUES LESS THAN (202404),
    -- ... 更多分区
    PARTITION p_future VALUES LESS THAN MAXVALUE
);

-- 财务记录表按年分区
ALTER TABLE financial_records PARTITION BY RANGE (YEAR(record_date)) (
    PARTITION p2023 VALUES LESS THAN (2024),
    PARTITION p2024 VALUES LESS THAN (2025),
    PARTITION p2025 VALUES LESS THAN (2026),
    PARTITION p_future VALUES LESS THAN MAXVALUE
);
```

## 3. Redis缓存设计

### 3.1 缓存策略

#### 3.1.1 缓存分类
- **热点数据缓存**: 用户信息、系统配置
- **会话缓存**: 用户登录状态、权限信息
- **计数器缓存**: 访问统计、点赞数量
- **队列缓存**: 异步任务队列
- **分布式锁**: 防止并发操作

#### 3.1.2 Key命名规范
```
项目前缀:模块:类型:标识
例如：
xlxumu:user:info:123456        # 用户信息
xlxumu:farm:stats:789          # 养殖场统计
xlxumu:session:token:abc123    # 会话token
xlxumu:lock:order:456789       # 订单锁
```

### 3.2 具体缓存设计

#### 3.2.1 用户相关缓存
```redis
# 用户基本信息 (Hash)
HSET xlxumu:user:info:123456 
  id 123456
  username "farmer001"
  phone "13800138000"
  status 1
  last_login_at "2024-01-20 10:30:00"
EXPIRE xlxumu:user:info:123456 3600

# 用户权限 (Set)
SADD xlxumu:user:permissions:123456 "user:view" "farm:create" "animal:manage"
EXPIRE xlxumu:user:permissions:123456 1800

# 用户会话 (String)
SET xlxumu:session:token:abc123def456 123456
EXPIRE xlxumu:session:token:abc123def456 7200
```

#### 3.2.2 业务数据缓存
```redis
# 养殖场统计 (Hash)
HSET xlxumu:farm:stats:789
  total_animals 150
  healthy_animals 145
  sick_animals 5
  total_value 50000.00
  last_updated "2024-01-20 15:30:00"
EXPIRE xlxumu:farm:stats:789 1800

# 热门动物品种 (ZSet)
ZADD xlxumu:animal:breeds:popular 100 "杜洛克猪" 95 "长白猪" 90 "大白猪"
EXPIRE xlxumu:animal:breeds:popular 3600

# 系统配置 (Hash)
HSET xlxumu:system:config
  site_name "畜牧养殖管理平台"
  max_upload_size "10MB"
  default_page_size "20"
EXPIRE xlxumu:system:config 86400
```

#### 3.2.3 计数器缓存
```redis
# 日访问量 (String)
INCR xlxumu:stats:daily_visits:2024-01-20
EXPIRE xlxumu:stats:daily_visits:2024-01-20 86400

# 用户在线数 (Set)
SADD xlxumu:stats:online_users 123456 789012 345678
EXPIRE xlxumu:stats:online_users 300

# 订单数量统计 (Hash)
HINCRBY xlxumu:stats:orders:2024-01-20 total 1
HINCRBY xlxumu:stats:orders:2024-01-20 pending 1
EXPIRE xlxumu:stats:orders:2024-01-20 86400
```

### 3.3 缓存更新策略

#### 3.3.1 Cache-Aside模式
```python
def get_user_info(user_id):
    # 先从缓存获取
    cache_key = f"xlxumu:user:info:{user_id}"
    user_info = redis.hgetall(cache_key)
    
    if user_info:
        return user_info
    
    # 缓存未命中，从数据库获取
    user_info = db.get_user(user_id)
    if user_info:
        # 写入缓存
        redis.hset(cache_key, mapping=user_info)
        redis.expire(cache_key, 3600)
    
    return user_info

def update_user_info(user_id, data):
    # 更新数据库
    db.update_user(user_id, data)
    
    # 删除缓存
    cache_key = f"xlxumu:user:info:{user_id}"
    redis.delete(cache_key)
```

#### 3.3.2 Write-Through模式
```python
def update_farm_stats(farm_id, stats):
    # 同时更新数据库和缓存
    db.update_farm_stats(farm_id, stats)
    
    cache_key = f"xlxumu:farm:stats:{farm_id}"
    redis.hset(cache_key, mapping=stats)
    redis.expire(cache_key, 1800)
```

## 4. MongoDB文档设计

### 4.1 集合设计

#### 4.1.1 操作日志集合 (operation_logs)
```javascript
{
  "_id": ObjectId("..."),
  "user_id": 123456,
  "username": "farmer001",
  "module": "animal",
  "action": "create",
  "method": "POST",
  "url": "/api/animals",
  "ip": "192.168.1.100",
  "user_agent": "Mozilla/5.0...",
  "request_data": {
    "name": "小猪001",
    "breed": "杜洛克",
    "farm_id": 789
  },
  "response_data": {
    "success": true,
    "data": {
      "id": 12345,
      "code": "PIG001"
    }
  },
  "status_code": 200,
  "execution_time": 150,
  "created_at": ISODate("2024-01-20T10:30:00Z")
}
```

#### 4.1.2 系统监控集合 (system_metrics)
```javascript
{
  "_id": ObjectId("..."),
  "metric_type": "performance",
  "metric_name": "api_response_time",
  "value": 120,
  "unit": "ms",
  "tags": {
    "endpoint": "/api/animals",
    "method": "GET",
    "status": "success"
  },
  "timestamp": ISODate("2024-01-20T10:30:00Z"),
  "server": "api-server-01"
}
```

#### 4.1.3 消息通知集合 (notifications)
```javascript
{
  "_id": ObjectId("..."),
  "user_id": 123456,
  "type": "health_alert",
  "title": "动物健康预警",
  "content": "您的养殖场有5头动物需要进行健康检查",
  "data": {
    "farm_id": 789,
    "animal_ids": [1001, 1002, 1003, 1004, 1005],
    "alert_level": "warning"
  },
  "status": "unread",
  "created_at": ISODate("2024-01-20T10:30:00Z"),
  "read_at": null,
  "expires_at": ISODate("2024-01-27T10:30:00Z")
}
```

### 4.2 索引设计

```javascript
// 操作日志索引
db.operation_logs.createIndex({ "user_id": 1, "created_at": -1 })
db.operation_logs.createIndex({ "module": 1, "action": 1 })
db.operation_logs.createIndex({ "created_at": -1 })

// 系统监控索引
db.system_metrics.createIndex({ "metric_type": 1, "timestamp": -1 })
db.system_metrics.createIndex({ "metric_name": 1, "timestamp": -1 })

// 消息通知索引
db.notifications.createIndex({ "user_id": 1, "status": 1, "created_at": -1 })
db.notifications.createIndex({ "type": 1, "created_at": -1 })
db.notifications.createIndex({ "expires_at": 1 }, { expireAfterSeconds: 0 })
```

## 5. 数据库优化

### 5.1 查询优化

#### 5.1.1 慢查询优化
```sql
-- 开启慢查询日志
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 2;
SET GLOBAL slow_query_log_file = '/var/log/mysql/slow.log';

-- 分析慢查询
EXPLAIN SELECT * FROM animals a 
JOIN farms f ON a.farm_id = f.id 
WHERE f.user_id = 123456 AND a.status = 1;

-- 优化后的查询
SELECT a.id, a.code, a.name, a.breed, f.name as farm_name
FROM animals a 
JOIN farms f ON a.farm_id = f.id 
WHERE f.user_id = 123456 AND a.status = 1
ORDER BY a.created_at DESC
LIMIT 20;
```

#### 5.1.2 索引优化
```sql
-- 分析索引使用情况
SHOW INDEX FROM animals;

-- 删除不必要的索引
DROP INDEX idx_animals_unused ON animals;

-- 创建复合索引
CREATE INDEX idx_animals_farm_status_created ON animals (farm_id, status, created_at);
```

### 5.2 存储优化

#### 5.2.1 表结构优化
```sql
-- 使用合适的数据类型
ALTER TABLE animals MODIFY COLUMN status TINYINT(1) NOT NULL DEFAULT 1;
ALTER TABLE animals MODIFY COLUMN weight DECIMAL(8,2) UNSIGNED;

-- 分离大字段
CREATE TABLE animal_details (
  animal_id BIGINT(20) UNSIGNED NOT NULL,
  description TEXT,
  images JSON,
  PRIMARY KEY (animal_id),
  CONSTRAINT fk_animal_details_animal_id FOREIGN KEY (animal_id) REFERENCES animals (id)
);
```

#### 5.2.2 分表策略
```sql
-- 按时间分表 - 操作日志
CREATE TABLE operation_logs_2024_01 LIKE operation_logs;
CREATE TABLE operation_logs_2024_02 LIKE operation_logs;

-- 按用户分表 - 大用户数据
CREATE TABLE user_data_0 LIKE user_data;
CREATE TABLE user_data_1 LIKE user_data;
-- 根据 user_id % 10 分表
```

### 5.3 性能监控

#### 5.3.1 关键指标监控
```sql
-- 查看数据库状态
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Queries';
SHOW GLOBAL STATUS LIKE 'Slow_queries';

-- 查看InnoDB状态
SHOW ENGINE INNODB STATUS;

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

#### 5.3.2 性能调优参数
```ini
# MySQL配置优化
[mysqld]
# 缓冲池大小 (物理内存的70-80%)
innodb_buffer_pool_size = 4G

# 日志文件大小
innodb_log_file_size = 256M

# 并发线程数
innodb_thread_concurrency = 16

# 查询缓存
query_cache_size = 128M
query_cache_type = 1

# 连接数
max_connections = 1000
max_connect_errors = 100000

# 表缓存
table_open_cache = 2000
```

## 6. 数据安全

### 6.1 数据加密

#### 6.1.1 敏感字段加密
```sql
-- 身份证号加密存储
ALTER TABLE users ADD COLUMN id_card_encrypted VARBINARY(255);

-- 手机号部分加密
UPDATE users SET phone_display = CONCAT(LEFT(phone, 3), '****', RIGHT(phone, 4));
```

#### 6.1.2 传输加密
- 使用SSL/TLS加密数据传输
- API接口使用HTTPS协议
- 数据库连接使用SSL

### 6.2 访问控制

#### 6.2.1 数据库用户权限
```sql
-- 创建应用数据库用户
CREATE USER 'xlxumu_app'@'%' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON xlxumu_main.* TO 'xlxumu_app'@'%';

-- 创建只读用户
CREATE USER 'xlxumu_readonly'@'%' IDENTIFIED BY 'readonly_password';
GRANT SELECT ON xlxumu_main.* TO 'xlxumu_readonly'@'%';

-- 创建备份用户
CREATE USER 'xlxumu_backup'@'localhost' IDENTIFIED BY 'backup_password';
GRANT SELECT, LOCK TABLES, SHOW VIEW ON xlxumu_main.* TO 'xlxumu_backup'@'localhost';
```

#### 6.2.2 行级安全
```sql
-- 创建安全策略视图
CREATE VIEW user_animals AS
SELECT * FROM animals 
WHERE farm_id IN (
  SELECT id FROM farms WHERE user_id = @current_user_id
);
```

### 6.3 数据备份

#### 6.3.1 备份策略
```bash
#!/bin/bash
# 全量备份脚本
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backup/mysql"
DB_NAME="xlxumu_main"

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

# 执行备份
mysqldump --single-transaction --routines --triggers \
  --user=xlxumu_backup --password=backup_password \
  $DB_NAME > $BACKUP_DIR/xlxumu_full_$DATE.sql

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

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

#### 6.3.2 增量备份
```bash
#!/bin/bash
# 增量备份脚本 (基于binlog)
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backup/mysql/binlog"
LAST_BACKUP_FILE="/backup/mysql/last_backup_position"

# 获取当前binlog位置
CURRENT_LOG=$(mysql -u root -p -e "SHOW MASTER STATUS\G" | grep File | awk '{print $2}')
CURRENT_POS=$(mysql -u root -p -e "SHOW MASTER STATUS\G" | grep Position | awk '{print $2}')

# 读取上次备份位置
if [ -f $LAST_BACKUP_FILE ]; then
  LAST_LOG=$(cat $LAST_BACKUP_FILE | grep File | awk '{print $2}')
  LAST_POS=$(cat $LAST_BACKUP_FILE | grep Position | awk '{print $2}')
else
  LAST_LOG=$CURRENT_LOG
  LAST_POS=4
fi

# 导出增量数据
mysqlbinlog --start-position=$LAST_POS $LAST_LOG > $BACKUP_DIR/incremental_$DATE.sql

# 更新备份位置
echo "File: $CURRENT_LOG" > $LAST_BACKUP_FILE
echo "Position: $CURRENT_POS" >> $LAST_BACKUP_FILE
```

## 7. 数据迁移

### 7.1 版本升级脚本

#### 7.1.1 数据库版本管理
```sql
-- 创建版本管理表
CREATE TABLE `schema_migrations` (
  `version` varchar(255) NOT NULL,
  `applied_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`version`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 版本1.0.0 -> 1.1.0 升级脚本
-- 添加动物体重历史表
CREATE TABLE `animal_weight_history` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `animal_id` bigint(20) unsigned NOT NULL,
  `weight` decimal(8,2) NOT NULL,
  `measured_at` timestamp NOT NULL,
  `notes` text,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_weight_history_animal_id` (`animal_id`),
  CONSTRAINT `fk_weight_history_animal_id` FOREIGN KEY (`animal_id`) REFERENCES `animals` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 记录版本
INSERT INTO schema_migrations (version) VALUES ('1.1.0');
```

### 7.2 数据清理

#### 7.2.1 定期清理脚本
```sql
-- 清理过期的操作日志 (保留3个月)
DELETE FROM operation_logs 
WHERE created_at < DATE_SUB(NOW(), INTERVAL 3 MONTH);

-- 清理软删除的数据 (删除超过1年的)
DELETE FROM users 
WHERE deleted_at IS NOT NULL 
  AND deleted_at < DATE_SUB(NOW(), INTERVAL 1 YEAR);

-- 清理临时数据
DELETE FROM temp_data 
WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 DAY);
```

## 8. 监控与告警

### 8.1 数据库监控

#### 8.1.1 关键指标
- **连接数**: 当前连接数/最大连接数
- **QPS**: 每秒查询数
- **慢查询**: 慢查询数量和比例
- **锁等待**: InnoDB锁等待情况
- **复制延迟**: 主从复制延迟时间

#### 8.1.2 监控脚本
```bash
#!/bin/bash
# 数据库监控脚本
MYSQL_USER="monitor"
MYSQL_PASS="monitor_password"

# 获取连接数
CONNECTIONS=$(mysql -u$MYSQL_USER -p$MYSQL_PASS -e "SHOW STATUS LIKE 'Threads_connected';" | awk 'NR==2{print $2}')

# 获取慢查询数
SLOW_QUERIES=$(mysql -u$MYSQL_USER -p$MYSQL_PASS -e "SHOW STATUS LIKE 'Slow_queries';" | awk 'NR==2{print $2}')

# 发送监控数据到监控系统
curl -X POST http://monitoring-system/api/metrics \
  -H "Content-Type: application/json" \
  -d "{
    \"metric\": \"mysql_connections\",
    \"value\": $CONNECTIONS,
    \"timestamp\": $(date +%s)
  }"
```

### 8.2 告警规则

#### 8.2.1 告警配置
```yaml
# 数据库告警规则
alerts:
  - name: mysql_connections_high
    condition: mysql_connections > 800
    severity: warning
    message: "MySQL连接数过高: {{ $value }}"
    
  - name: mysql_slow_queries_high
    condition: rate(mysql_slow_queries[5m]) > 10
    severity: critical
    message: "MySQL慢查询增长过快"
    
  - name: mysql_replication_lag
    condition: mysql_slave_lag_seconds > 60
    severity: critical
    message: "MySQL主从复制延迟: {{ $value }}秒"
```

## 9. 扩展规划

### 9.1 水平扩展

#### 9.1.1 读写分离
```python
# 数据库路由配置
DATABASE_ROUTERS = {
    'master': {
        'host': 'mysql-master.example.com',
        'port': 3306,
        'user': 'xlxumu_app',
        'password': 'password',
        'database': 'xlxumu_main'
    },
    'slaves': [
        {
            'host': 'mysql-slave1.example.com',
            'port': 3306,
            'user': 'xlxumu_readonly',
            'password': 'password',
            'database': 'xlxumu_main'
        },
        {
            'host': 'mysql-slave2.example.com',
            'port': 3306,
            'user': 'xlxumu_readonly',
            'password': 'password',
            'database': 'xlxumu_main'
        }
    ]
}
```

#### 9.1.2 分库分表
```python
# 分库分表策略
def get_database_shard(user_id):
    """根据用户ID获取分库"""
    shard_id = user_id % 4
    return f"xlxumu_shard_{shard_id}"

def get_table_shard(user_id, table_name):
    """根据用户ID获取分表"""
    shard_id = user_id % 10
    return f"{table_name}_{shard_id}"
```

### 9.2 垂直扩展

#### 9.2.1 服务拆分
- **用户服务数据库**: 用户、角色、权限相关表
- **养殖服务数据库**: 养殖场、动物、健康记录相关表
- **交易服务数据库**: 订单、支付、财务相关表
- **日志服务数据库**: 操作日志、监控数据相关表

#### 9.2.2 数据同步
```python
# 跨库数据同步
class DataSyncService:
    def sync_user_data(self, user_id, data):
        """同步用户数据到相关服务"""
        # 同步到养殖服务
        farming_db.update_user_cache(user_id, data)
        
        # 同步到交易服务
        trading_db.update_user_cache(user_id, data)
        
        # 发送消息队列通知
        message_queue.publish('user.updated', {
            'user_id': user_id,
            'data': data
        })
```

## 10. 总结

本数据库设计文档详细描述了畜牧养殖管理平台的数据库架构，包括：

### 10.1 设计亮点
- **完整的业务模型**: 覆盖用户管理、养殖管理、交易管理、财务管理等核心业务
- **灵活的权限体系**: 基于RBAC的权限管理，支持细粒度权限控制
- **高性能设计**: 合理的索引设计、分区策略、缓存机制
- **数据安全**: 敏感数据加密、访问控制、备份策略
- **可扩展性**: 支持读写分离、分库分表、服务拆分

### 10.2 技术特色
- **多数据库架构**: MySQL + Redis + MongoDB，各司其职
- **规范化设计**: 统一的命名规范、字段类型、索引策略
- **监控完善**: 全面的性能监控和告警机制
- **运维友好**: 自动化备份、版本管理、数据清理

### 10.3 后续优化
- 根据实际业务量调整分区策略
- 持续优化慢查询和索引设计
- 完善监控指标和告警规则
- 评估和实施分库分表方案

本设计为平台的稳定运行和未来扩展提供了坚实的数据基础。