猿问

从笛卡尔积中获取不同记录的算法

我有两个表(比如,A 和 B)。我的任务是将 B 与 A 同步,即如果 A 中存在但 B 中不存在,则将记录添加到 B;如果 B 中存在但 A 中不存在,则从 B 中删除记录。


A 和 B 可以有重复的记录,这样如果 A 中的记录是重复的,那么 B 也应该有重复的记录。A 和 B 中的样本数据


      **Table A**                              **Table B**

    id    identifier                      id       identifier

    100   capital                         1001     bat

    201   bat                             1002     bat

    202   bat                             1003     bat

                                          5010     keyboard

为此,我使用外连接从 A 和 B 获取记录,这样我的输出看起来像:


    A.id  B.id   identifier

    100   null    capital

    201   1001    bat

    201   1002    bat   

    201   1003    bat

    202   1001    bat

    202   1002    bat

    202   1003    bat

    null  5010    keyboard

因此在上面的例子中,100 和 5010 分别是添加和删除候选,这很容易计算。


问题是发现 1003 也是删除候选。由于 201 和 202 分别映射到 1001 和 1002。


我可以在数据库中做到这一点,通过对数据库中的重复项进行编号,就像在MYSQL 中所做的那样 :在自联接时避免重复记录的笛卡尔积 但是由于一些限制,我只能使用外联接加载上述格式的数据。因此,我需要 JAVA 中的算法来执行上述操作。提前致谢。


慕后森
浏览 163回答 2
2回答

手掌心

这是我解决这个问题的方法:从表 A 和表 B 中获取数据。表 A 和表 B 的桶数据按标识符,使用:&nbsp;&nbsp;&nbsp;&nbsp;Map<String,&nbsp;SameBucketObject>其中 key 是 'identifier' 并且 SameBucketObject 是:&nbsp; &nbsp; class SameBucketObject{&nbsp; &nbsp; &nbsp; private List<String> idsOfA;&nbsp; &nbsp; &nbsp; private List<String> idsOfB;&nbsp; &nbsp; // getter, setters, addToList statements&nbsp;&nbsp;&nbsp; &nbsp; }基本上,我按标识符将表 A 和表 B 的所有元素分组。在每个桶中,检查 A 的idsOfA元素和 B的元素的计数idsOfB,如果&nbsp; &nbsp; sizeOf(idsOfA) < sizeOf(idsOfB) -> add elements with ids in idsOfB List from Table B to Table A&nbsp; &nbsp; sizeOf(idsOfA) > sizeOf(idsOfB) -> delete sizeOf(idsOfA) - sizeOf(idsOfB) elements from A from last.&nbsp; &nbsp; sizeOf(idsOfA) = sizeOf(idsOfB) -> no action.这种方法不使用额外的空间
随时随地看视频慕课网APP

相关分类

Java
我要回答