如何连接两个SQLite表,其中键是不完全相同的整数值?

ig9co6j1  于 2023-01-31  发布在  SQLite
关注(0)|答案(1)|浏览(142)

我有两个表,其中的on连接键不是完全相同的整数值。我如何使用这些键上的最佳匹配(差异应该是最小的)进行连接?

CREATE TABLE t1(
       "size" TEXT,
       filename TEXT
     );
     
     -- ----------------------------
     -- Records of matching
     -- ----------------------------
     INSERT INTO "main"."t1" VALUES (1162775, file1);
     INSERT INTO "main"."t1" VALUES (1145387, file1);
     INSERT INTO "main"."t1" VALUES (1388613, file1);
     INSERT INTO "main"."t1" VALUES (1306413, file1);
     INSERT INTO "main"."t1" VALUES (1792882, file1);
     INSERT INTO "main"."t1" VALUES (1798382, file1);
     INSERT INTO "main"."t1" VALUES (878147,  file1);
     INSERT INTO "main"."t1" VALUES (2614277, file1);
     INSERT INTO "main"."t1" VALUES (838639,  file1);
     INSERT INTO "main"."t1" VALUES (3053906, file1);
     INSERT INTO "main"."t1" VALUES (1019579, file1);
     INSERT INTO "main"."t1" VALUES (3234508, file1);
     INSERT INTO "main"."t1" VALUES (2442681, file1);

     CREATE TABLE t2(
        "info" Text,
        readysize TEXT
     );
     
     -- ----------------------------
     -- Records of matching
     -- ----------------------------
     INSERT INTO "main"."t2" VALUES (info1, 1162780);
     INSERT INTO "main"."t2" VALUES (info1, 1145392);
     INSERT INTO "main"."t2" VALUES (info1, 1388620);
     INSERT INTO "main"."t2" VALUES (info1, 1306420);
     INSERT INTO "main"."t2" VALUES (info1, 1792888);
     INSERT INTO "main"."t2" VALUES (info1, 1798388);
     INSERT INTO "main"."t2" VALUES (info1, 878152 );
     INSERT INTO "main"."t2" VALUES (info1, 2614284);
     INSERT INTO "main"."t2" VALUES (info1, 838644 );
     INSERT INTO "main"."t2" VALUES (info1, 3053912);
     INSERT INTO "main"."t2" VALUES (info1, 1019584);
     INSERT INTO "main"."t2" VALUES (info1, 3234516);
     INSERT INTO "main"."t2" VALUES (info1, 2442688);

These key relation should be obtained as best fit:

 1162775 ->  1162780
 1145387 ->  1145392
 1388613 ->  1388620
 1306413 ->  1306420        
 1792882 ->  1792888
 1798382 ->  1798388
 878147 ->    878152 
 2614277 ->  2614284
 838639 ->    838644
 3053906 ->  3053912
 1019579 ->  1019584
 3234508 ->  3234516
 2442681 ->  2442688

我希望select * from t1 join t2 on t1.size (match best fit) t2.readysizeon部分,以便第一行的on应匹配11627751162780,依此类推。
PS:嗯,我认为on键可以这样做:

select * from t1 join t2 on abs(t1.size - t2.readysize) < 10 and ((t1.size >= t2.readysize) or (t1.size <= t2.readysize))

这有意义吗?所以我定义了一个delta,最大为10 fidoee。,绝对位置由and限制。

oknrviil

oknrviil1#

使用CROSS JOIN的表和聚合,利用SQLite的空列特性:

SELECT *, 
       MIN(ABS(t1.size - t2.readysize)) AS diff
FROM t1 JOIN t2
GROUP BY t1.rowid;

您可以使用主键t1更改rowid
请参见demo

相关问题