Files
pj_service_cloud/db/20261004_wallet_transaction_page_index.sql
2026-10-21 19:39:59 +08:00

48 lines
3.1 KiB
SQL
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- 钱包流水分页接口慢查询索引优化(生产 PolarDB,只加索引不改代码)
-- 影响接口:/wallet-transaction/page-join 及 page-cz / page-jz / page-xf / page-tk / page-th / app/page
-- (后端全部走 WalletTransactionMapper.scopePageList + count,SQL 形态一致)
--
-- 慢因:wallet_transaction 只有 PRIMARY(id)、idx_dept_id(wallet_id)、
-- idx_wallet_transaction_user_time(user_id,create_time)、idx_version(wallet_id,version),
-- 管理端列表 SQL(WHERE tenant_id=? AND del_flag='0' ORDER BY create_time DESC,user_id DESC LIMIT 10
-- + 同条件 COUNT)无任何可用索引 → 全表扫描 + filesort,大表上每次翻页执行两遍。
--
-- 注意:slowlog_optimization_20260826/01_add_indexes.sql 里提过同样的两条索引,
-- 但测试服与本地库均未建过,生产大概率也没有;执行前先按下面步骤核对。
--
-- ============ 执行前核对 ============
-- SHOW INDEX FROM pjcloudx_wallet.wallet_transaction;
-- 若下述索引名已存在且列一致,跳过对应条目;列不一致先停下人工确认,不要盲目重建。
--
-- ============ 执行方式 ============
-- InnoDB 二级索引创建默认 ONLINE(不锁 DML),但大表建索引有 IO 消耗,
-- 生产 IOPS 上限 8000,请低峰期逐条执行、每条间隔观察,不要并发跑。
-- P0-1:默认列表 / 时间范围 / COUNT。
-- 覆盖 WHERE tenant_id=? AND del_flag='0' 的等值前缀,且 (create_time,user_id) 与
-- ORDER BY create_time DESC, user_id DESC 完全同序,可 Backward index scan,LIMIT 10 只读 10 行;
-- COUNT 走该索引即为覆盖索引扫描(Using index)。
CREATE INDEX idx_wallet_tx_tenant_del_ct_uid
ON pjcloudx_wallet.wallet_transaction (tenant_id, del_flag, create_time, user_id);
-- P0-2:按业务类型过滤的页面(充值/记账/消费/退款/退还)。
-- biz_type 为 tinytext,必须前缀索引;稀有类型(如退款)优化器会用本索引 ref 定位后再倒序扫。
CREATE INDEX idx_wallet_tx_tenant_del_biz_ct_uid
ON pjcloudx_wallet.wallet_transaction (tenant_id, del_flag, biz_type(8), create_time, user_id);
-- ============ 执行后验证(本地已 EXPLAIN 验证,生产建完再跑一遍确认) ============
-- 期望:key = idx_wallet_tx_tenant_del_ct_uid,Extra 含 Backward index scan 且无 Using filesort
-- EXPLAIN SELECT a.* FROM pjcloudx_wallet.wallet_transaction a
-- LEFT JOIN pjcloudx_wallet.wallet_manage m ON m.id = a.wallet_id AND m.del_flag='0'
-- WHERE a.del_flag='0' AND a.tenant_id=1
-- ORDER BY a.create_time DESC, a.user_id DESC LIMIT 10;
--
-- 期望:key = idx_wallet_tx_tenant_del_ct_uid,Extra = Using index
-- EXPLAIN SELECT COUNT(*) FROM pjcloudx_wallet.wallet_transaction a
-- WHERE a.del_flag='0' AND a.tenant_id=1;
--
-- 期望:key = idx_wallet_tx_tenant_del_biz_ct_uid,Extra 含 Backward index scan
-- EXPLAIN SELECT a.* FROM pjcloudx_wallet.wallet_transaction a
-- WHERE a.del_flag='0' AND a.tenant_id=1 AND a.biz_type IN ('9')
-- ORDER BY a.create_time DESC, a.user_id DESC LIMIT 10;