找到MySQL中最小的识别子集

时间:2015-04-09 04:14:48

标签: mysql

我有一张桌子,让我们说field1field2field1是集合的标识符,field2包含集合的成员。现在,问题是,如何找出唯一能够唯一找到给定field2的{​​{1}}值?

示例数据

field1

我正在寻找一个查询,其中+------+------+ |field1|field2| | 1 | A | | 1 | B | | 1 | C | | 2 | A | | 2 | C | | 2 | D | | 3 | B | | 3 | D | +------+------+ 作为参数返回1,2返回(A,B)(A,D)两者都是好的(C,D)返回3。如果通用案例太难了,那么让我们问:是否有这样的一对做到这一点。

一旦我有这样一对,我可以将其插入此查询:

(B,D)

并且只获得一行。

我尝试了类似SELECT DISTINCT field1 FROM t t1 INNER JOIN t t2 USING(field1) WHERE t1.field2 = 'A' AND t2.field2 = 'B' 的内容,但这显然无效。

2 个答案:

答案 0 :(得分:2)

您编写一个子查询,返回每个field2的所有field1值对。然后使用此连接与其自身,找到具有相同field2值但不同field1的对。然后通过NULL检查将其排除在外,并为每个field1留下唯一对。

SELECT subq1.field1, subq1.a, subq1.b
FROM (
    SELECT t1.field1, t1.field2 AS a, t2.field2 AS b
    FROM t AS t1
    JOIN t AS t2 ON t1.field1 = t2.field1 AND t1.field2 < t2.field2
) as subq1
LEFT JOIN (
    SELECT t1.field1, t1.field2 AS a, t2.field2 AS b
    FROM t AS t1
    JOIN t AS t2 ON t1.field1 = t2.field1 AND t1.field2 < t2.field2
) AS subq2 ON subq1.field1 != subq2.field1 AND subq1.a = subq2.a AND subq1.b = subq2.b
WHERE subq2.field1 IS NULL

DEMO

答案 1 :(得分:0)

我写了下面的查询

 SELECT  temp. field1,temp.firstValue,temp.secondValue
 FROM  (SELECT   table1.field1 , table1.field2 firstValue ,table2.field2 secondValue FROM T table2 ,T table1 
    WHERE table1.field1 = table2.field1 AND table2.field2<> table1.field2 AND table1.field2 < table2.field2  

    )  temp
  GROUP BY   temp. field1,temp.firstValue 

它会在下面给你

field1  firstValue  secondValue
------  ----------  -----------
     1  A           B          
     1  B           C          
     2  A           C          
     2  C           D          
     3  B           D          

如果输入2(A,C)(A,D)就足够了,请告诉我