需求场景
表father与表son有父子级关系,需要一张表维护father_id与son_id的关系,同时需要保存每次变更的历史,需要满足历史变更查询、根据版本查询关联、版本数据维护等场景
备注:
– data_associated_table 关联关系表
– id: 主键
– del_flag: 删除标识(用来表示取消关系,为了历史变更做逻辑删除,1删除,0生效)
– father_id: 父级数据主键(#{fatherId}为mybatis的参数)
– son_id: 子级数据主键(#{sonId}为mybatis的参数)
– version: 版本号
- 新增
查询出最新的版本+1,增量保存
insert into data_associated_table(id, del_flag, son_id, father_id, version)
select replace(uuid_short(), ‘-’, ‘’), 0, #{sonId}, #{fatherId}, max(a.version) + 1
from ent_industry_code a; - 删除
删除整个版本:删除版本号为查询版本的所有记录
delete from data_associated_table where version = #{version}; - 修改
取消关联:和新增逻辑类似,del_flag标识为1 - 查询
查询出所有小于或等于查询版本的记录,可分开查询,等于查询版本+小于查询版本(需要排除等于的)
select b.*
from data_associated_table b
inner join (
select a.father_id, a.son_id, max(a.version) as max_version
from data_associated_table a
where a.version <= #{version}
group by a.father_id, a.son_id
) c
on b.father_id = c.father_id
and b.son_id = c.son_id
and b.version = c.max_version
where b.del_flag = 0;