-- ============================================ -- 数据库索引优化迁移 -- 创建时间: 2026-06-05 -- 目的: 优化高频查询的性能 -- ============================================ SET NAMES utf8mb4; -- ------------------------------------------- -- 1. 订单状态+创建时间复合索引 -- 用途: 后台订单管理、用户订单列表按时间排序 -- 场景: SELECT * FROM rental_orders WHERE status = ? ORDER BY created_at DESC -- ------------------------------------------- ALTER TABLE rental_orders ADD INDEX idx_rental_orders_status_created_at (status, created_at DESC); -- ------------------------------------------- -- 2. 钱包流水按用户+业务类型+时间查询 -- 用途: 用户查看特定类型的流水记录 -- 场景: SELECT * FROM wallet_ledger WHERE user_id = ? AND biz_type = ? ORDER BY created_at DESC -- ------------------------------------------- ALTER TABLE wallet_ledger ADD INDEX idx_wallet_ledger_user_biz_created (user_id, biz_type, created_at DESC); -- ------------------------------------------- -- 3. 订单结算状态查询优化 -- 用途: 查询待结算订单、按号主查询结算记录 -- 场景: SELECT * FROM rental_orders WHERE settlement_status = ? AND owner_id = ? ORDER BY created_at -- ------------------------------------------- ALTER TABLE rental_orders ADD INDEX idx_rental_orders_settlement (settlement_status, owner_id, created_at); -- ------------------------------------------- -- 4. 商品发布时间查询优化 -- 用途: 首页商品列表按发布时间排序 -- 场景: SELECT * FROM rental_listings WHERE status = 'active' AND review_status = 'approved' ORDER BY published_at DESC -- 注意: 使用部分索引(MySQL 8.0+)只索引可用商品 -- ------------------------------------------- ALTER TABLE rental_listings ADD INDEX idx_rental_listings_published (status, review_status, published_at DESC); -- 如果需要进一步优化,可以考虑添加 in_transaction 列 -- 但当前索引已经足够覆盖大部分查询 -- ------------------------------------------- -- 5. 用户实名认证状态查询 -- 用途: 查询未实名用户、查询活跃且已实名用户 -- 场景: SELECT * FROM users WHERE realname_status = 'verified' AND status = 'active' -- ------------------------------------------- ALTER TABLE users ADD INDEX idx_users_realname_status (realname_status, status); -- ============================================ -- 索引创建完成 -- ============================================ -- 验证索引创建情况(可选,用于开发环境验证) -- SHOW INDEX FROM rental_orders WHERE Key_name LIKE 'idx_rental_orders_%'; -- SHOW INDEX FROM wallet_ledger WHERE Key_name LIKE 'idx_wallet_ledger_%'; -- SHOW INDEX FROM rental_listings WHERE Key_name LIKE 'idx_rental_listings_%'; -- SHOW INDEX FROM users WHERE Key_name LIKE 'idx_users_%';