查找具有相同B列值集的MySQL条目,以获取其公共列A值

时间:2010-05-18 19:37:07

标签: mysql

我有:

+----+------+------+
| id | A    | B    |
+----+------+------+
|  1 |    1 |    1 |  <
|  2 |    1 |    2 |  <
|  3 |    2 |    2 | 
|  4 |    2 |    3 | 
|  5 |    3 |    1 |  <
|  6 |    3 |    2 |  <
|  7 |    4 |    4 | 
|  8 |    4 |    5 | 
+----+------+------+

我需要为共同的A值选择具有相同B值集的条目。因此,在这种情况下,我需要id 1,2和5,6,因为在这些情况下,B值的序列是1,2。

这可能吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

这是你想要的吗?

SELECT t1.ID
FROM TableName AS t1
  INNER JOIN TableName AS t2 ON t1.B=t2.B AND NOT t1.A=t2.A

答案 1 :(得分:0)

以下是我提出的建议:

SELECT IDs FROM
(SELECT GROUP_CONCAT(id) AS IDs, a FROM foo GROUP BY a) Y
WHERE a IN
(SELECT Ta.a FROM (SELECT a, GROUP_CONCAT(b) AS c FROM foo GROUP BY a) Ta
JOIN (SELECT a, GROUP_CONCAT(b) AS c FROM foo GROUP BY a) Tb USING (c) WHERE T
a.a <> Tb.a)

结果:

+------+
| IDs  |
+------+
| 1,2  |
| 5,6  |
+------+
2 rows in set (0.00 sec)

我们的想法是SELECT a, GROUP_CONCAT(b) AS c FROM foo GROUP BY a上的等连接为我们提供了具有相同b值的a值。 (这可能需要作为相关子查询进行细化,因为更多数据被添加到表中。)

然后,我们选择a列表中值为a的ID,其值为b