针对查询用户过去三十天流水的需求,如何设计数据库表结构?

1 个回答

  • 小王子-B152
    不妨大胆一点,很多事情都没有答案。

    作用

    该设计用于同时维护账户当前状态和账户变动明细,支持审计、追溯、数据分析,以及按用户和时间查询历史流水,例如查询某个用户过去三十天的账户变动记录。

    原理

    1. 账号表保存当前状态

    账号表保存用户账户的最新余额等信息:

    • uid:用户账号 ID,作为主键。
    • balance:账户余额,并通过约束保证余额不能小于 0。
    • xid_num:产生或变更记录的作业号,可用于关联同一笔业务中的多个账户变更。
    • crt_time:记录创建时间。
    • mod_time:记录最后修改时间。

    示例结构:

    create table tbl
    (
      xid_num int8,
      uid int primary key,
      balance float8 check (balance >= 0),
      crt_time timestamp default now(),
      mod_time timestamp
    );
    

    2. 流水表保存每次账户变更

    流水表记录用户账户每次新增、修改或删除前后的完整数据:

    • xid_num:作业号,用于追踪同一笔交易或批处理任务。
    • uid:用户账号 ID。
    • crt_time:流水产生时间,用于按时间范围查询。
    • audit_old:变更前的记录,使用 hstore 保存旧值。
    • audit_new:变更后的记录,使用 hstore 保存新值。
    • tag:操作类型,例如 insert、update、delete。

    示例结构:

    create table tbl_history (
      xid_num int8,
      uid int,
      crt_time timestamp default now(),
      audit_old hstore,
      audit_new hstore,
      tag text
    );
    

    3. 建立查询所需索引

    为了支持按用户和时间查询流水,需要建立索引:

    • 在 uid 上建索引,用于快速定位某个用户的流水。
    • 在 xid_num 上建索引,用于按作业号追踪相关变更。
    • 在 crt_time 上使用 BRIN 索引,因为流水数据天然按时间顺序写入,BRIN 索引适合这种时序大表。
    create index idx_tbl_history_xid on tbl_history (xid_num);
    create index idx_tbl_history_uid on tbl_history (uid);
    create index idx_tbl_history_time on tbl_history using brin(crt_time);
    

    查询用户过去三十天流水时,可以通过 uid 与 crt_time 的时间范围条件过滤记录。

    4. 可选:按时间分区

    由于流水表具有明显的时序特征,可以按 crt_time 做范围分区,例如按月分区。这样查询近三十天流水时,只需要扫描相关时间分区,并便于后续归档或清理历史数据。

    create table tbl_history (
      xid_num int8,
      uid int,
      crt_time timestamp default now(),
      audit_old hstore,
      audit_new hstore,
      tag text
    )
    partition by range(crt_time);
    
    参考来源:https://developer.aliyun.com/article/118720
    发布于 2026-03-07 17:13 •IP属地 北京
    举报
    评论
    收藏