如何把结构相似(不完全相同)的表结构合并,然后部分数据迁移都另一张表中(不知道说清楚没得^o^)


三、某系统根据用户购买数据已经生成了同时购买同一类别下两个产品的数据,现需要使用该数据,生成同时购买同一类别下三个产品的数据,请设计并简要实现:
说明:
1、表结构如下:

   
  create table purchasetogether (
  
ProductId1 varchar(50) not null,
ProductId2 varchar(50) not null,
CategoryId int(10) not null,
CustomerCount int(10) not null,
CustomerIds text not null,
primary key (ProductId1, ProductId2),
key CategoryId (CategoryId)
); create table multipurchasetogether (
ProductId1 varchar(50) not null,
ProductId2 varchar(50) not null,
ProductId3 varchar(50) not null,
CategoryId int(10) not null,
CustomerCount int(10) not null,
CustomerIds text not null,
primary key (ProductId1, ProductId2, ProductId3),
key CategoryId (CategoryId)
);

ProductId1: 同时购买的第一个产品id,已有数据已经保证ProductId1 < ProductId2
ProductId2: 同时购买的第二个产品id
CategoryId: 产品类别id
CustomerCount: 同时购买ProductId1和ProductId2的用户数量
CustomerIds: 同时购买ProductId1和ProductId2的所有用户id列表,用户id间以逗号分隔
2、该表的数据量为千万或者上亿级,处理时需要按照每个产品类别(Category)进行,单个类别的数据量可能会达到百万级。设计和实现时可以只考虑处理配置的单个类别。
3、生成的数据放入multipurchasetogether表,表结构与purchasetogether类似,并且需要保证ProductId1<ProductId2<ProductId3。
4、数据库访问接口与题目一相同。

数据库 java

auxox 10 years, 4 months ago

说下思路吧, 初看起来挺唬人, 表数据量千万或亿级; 但是ProductId1, ProductId2, ProductId3都在同一个类别下, 可以分类别处理, 一个类别数据量为百万级.

完全在数据库中做, 会存在数据的大量重复读取, 考虑把数据放在内存中处理; 建两级hash表:

数据结构

第一级hash: key为ProductId1, value 为purchasetogether 中ProductId1字段的所有记录;
第二季hash: key为purchasetogether 中的ProductId2, value为 HashSet{customerid}

这样, 查找某个customerId是否购买了某个ProductId1和ProductId2的时间为O(1).

因为按类别处理, 数量级为百万级. 这个两级hash表放入内存还是有可能的. 如果不行, 考虑把此hash表按第一级hash的key排序分组, 序列化写入硬盘, 需要的时候从硬盘读回.

另外, 因为ProductId1<ProductId2, 已经处理过的ProductId1可以直接从二级Hash表里删除.

运算步骤

生成同时购买同一类别下三个产品的数据:
遍历二级hash表中所有的(ProductId1,ProductId2, customerIds), 设ProductId1=a, ProductId2=b, customerIds=c;
在二级hash表中找ProductId1=b的所有(ProductId2=d,customerIds=e),
则结果数据为(ProductId1=a, ProductId2=b,ProductId2=d,customerIds=(e和c的交集))

将结果数据批量写回multipurchasetogether表.

lll-lll answered 10 years, 4 months ago

Your Answer