简体   繁体   English

仅加入两个表的分区

[英]Join only the partitions of two tables

SQL Server 2008 SQL Server 2008

Table A looks like: 表A看起来像:

A_ID  v1   v2   v3
---------------------------
 1    d    e    f
 1    a    b    c
 1    a    b    d
 2    d    a    b
 2    e    f    g
 3    d    e    f
 3    e    f    g
 3    d    a    b

and Table B is similar: 和表B类似:

B_ID  v1   v2   v3
---------------------------
 Q    a    b    c
 Q    b    a    c
 Q    a    b    d
 R    d    e    f
 R    a    b    c
 R    d    e    f
 P    e    f    g
 P    d    a    b

What I need back from these two tables are the (A_ID, B_ID) pairs, if any, where each row of Table B where B_ID = any one value has one matching row in Table A where A_ID = any one value. 我需要从这两个表中得到的是(A_ID,B_ID)对,如果有的话,其中表B的每一行,其中B_ID =任何一个值在表A中具有一个匹配的行,其中A_ID =任何一个值。 In other words, I need to the complete matching set in A for each full set of triples in B--no super sets or subsets. 换句话说,对于B中的每个完整三元组,我需要A中的完全匹配集 - 没有超集或子集。 The value of B_ID and A_ID is immaterial. B_ID和A_ID的值并不重要。

I thought partitioning would be the way to go, since I already have the column that naturally partitions A and B, and I also thought I could pre-select which paritions where JOINed by ensuring only partitions with matching numbers of rows would be attempting. 我认为分区是可行的方法,因为我已经有了自然分区A和B的列,我还以为我可以通过确保只有具有匹配行数的分区来尝试预先选择JOIN的分区。 I haven't been able to do either--partitioning both tables was easy, but I see no way to tell the join to only act on the partitions. 我无法做到 - 对两个表进行分区很容易,但我认为没有办法告诉联接只能对分区执行操作。

In this example, (2,P) would be returned because all rows in Set P match all rows in Set 2. Result (1, R) would NOT be returned because all rows of Set R are not matched by all rows of Set 1, etc. 在此示例中,将返回(2,P),因为Set P中的所有行都匹配Set 2中的所有行。将不返回Result(1,R),因为Set R的所有行都不与Set 1的所有行匹配等

Using symetric difference : 使用symetric difference

SELECT DISTINCT a1.A_ID, b1.B_ID
FROM A a1,B b1
WHERE NOT EXISTS (
                   (SELECT v1,v2,v3
                   FROM A WHERE A.A_ID = a1.A_ID
                   EXCEPT
                   SELECT v1,v2,v3
                   FROM B WHERE B.B_ID = b1.B_ID
                   ) 
                   UNION ALL
                   (
                   SELECT v1,v2,v3
                   FROM B WHERE B.B_ID = b1.B_ID
                   EXCEPT
                   SELECT v1,v2,v3
                   FROM A WHERE A.A_ID = a1.A_ID)
                 );

LiveDemo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM