diff --git a/db_migrations/add_active_location_indexes.sql b/db_migrations/add_active_location_indexes.sql new file mode 100644 index 0000000..b0a2840 --- /dev/null +++ b/db_migrations/add_active_location_indexes.sql @@ -0,0 +1,53 @@ +-- ============================================================================= +-- 一次性迁移:为「活跃库位推荐」查询补索引 +-- +-- 背景 +-- get_active_locations(company_name, days, top_n) 要扫三张流水/库存表的 +-- 时间字段,并逐一 JOIN 回库存表取库位: +-- trans_outbound.outbound_time → JOIN stock_* ON (source_table, stock_id) +-- trans_borrow.borrow_time → JOIN stock_buy ON (source_table, stock_id) +-- stock_buy.in_date / stock_semi.production_date / stock_product.production_date +-- +-- 现状(实测 pg_indexes): +-- stock_buy / stock_semi / stock_product 的 warehouse_location 已建索引 +-- trans_outbound、trans_borrow 只有主键索引,时间字段和 (source_table, +-- stock_id) JOIN 键都没有索引;三张库存表的时间字段也没有索引。 +-- +-- 为什么现在加(诚实说明) +-- 实测 EXPLAIN ANALYZE:当前数据量下(trans_outbound 900 行、stock_buy 2018 行) +-- 该查询耗时仅 1.3ms,且全走 Seq Scan + Hash Join —— 这是小表下的**正确** +-- 计划,索引也不会被选中。所以本次加索引不是为了修当前的慢,而是为 +-- 90 天/半年后的数据增长做前瞻,避免那时才临时补。 +-- 加完索引后本查询在当前数据量下仍会走 Seq Scan,属预期行为。 +-- +-- 执行: docker exec -i inventory_db psql -U test -d inventory_system < 本文件 +-- ============================================================================= +BEGIN; + +-- 出库:按时间窗口过滤 +CREATE INDEX IF NOT EXISTS ix_trans_outbound_time + ON trans_outbound(outbound_time); + +-- 出库:回查库存表取库位的 JOIN 键 +CREATE INDEX IF NOT EXISTS ix_trans_outbound_source_stock + ON trans_outbound(source_table, stock_id); + +-- 借用:按时间窗口过滤 +CREATE INDEX IF NOT EXISTS ix_trans_borrow_time + ON trans_borrow(borrow_time); + +-- 借用:回查库存表取库位的 JOIN 键 +CREATE INDEX IF NOT EXISTS ix_trans_borrow_source_stock + ON trans_borrow(source_table, stock_id); + +-- 入库没有独立流水表,直接以库存表自身的入库/生产时间计时 +CREATE INDEX IF NOT EXISTS ix_stock_buy_in_date + ON stock_buy(in_date); + +CREATE INDEX IF NOT EXISTS ix_stock_semi_production_date + ON stock_semi(production_date); + +CREATE INDEX IF NOT EXISTS ix_stock_product_production_date + ON stock_product(production_date); + +COMMIT; diff --git a/inventory-web/src/views/stock/stocktake/index.vue b/inventory-web/src/views/stock/stocktake/index.vue index 7c5f12d..809c20a 100644 --- a/inventory-web/src/views/stock/stocktake/index.vue +++ b/inventory-web/src/views/stock/stocktake/index.vue @@ -134,6 +134,10 @@
💡 提示:勾选父级货架,将自动涵盖其下属的所有末级库位及库存。
+