0

我有一个看起来像的表:

 a | b
---+---
 1 | a
 2 | a
 3 | a

 1 | b
 3 | b

 2 | c
 3 | c

它表示多对多关系 a<->b。我想获得所有现有的关系 a<->count(b)<->a,例如:

 a1 | a2 | count
----+----+-------
 1  |  2 |     1         #1<->a<->2
 1  |  3 |     2         #1<->(a,b)<->3

 2  |  1 |     1         #duplicate for 1<->a<->2
 2  |  3 |     2         #2<->(a,c)<->3

 3  |  1 |     2         #duplicate for 1<->(a,b)<->3 
 3  |  1 |     2         #duplicate for 2<->(a,c)<->3

我已经为单个 a 进行了管理,但不知道如何循环遍历所有内容:

SELECT
 '1' AS a1,
 t1.a AS a2,COUNT(t1.b)
FROM 
 a_b t1
INNER JOIN(
  SELECT
   b
  FROM a_b
  WHERE
   a = '1'
  ) t2
ON
 t1.b = t2.b
WHERE t1.a != '1'
GROUP BY t1.a
ORDER BY t1.a;

 a1 | a2 | count
----+----+-------
 1  |  2 |     1
 1  |  3 |     2

如果不交叉加入 a_b 本身或循环外部脚本,是否可以实现?

这是 SQLFiddle http://www.sqlfiddle.com/#!1/8b53a/1/0

TIA

4

2 回答 2

2

我认为这是一个带有聚合的基本“加入”查询:

select ab1.a, ab2.a, count(*)
from a_b ab1 join
     a_b ab2
     on ab1.b = ab2.b and ab1.a <> ab2.a
group by ab1.a, ab2.a
于 2013-09-07T11:59:08.037 回答
0

对 Gordon Linoff 的解决方案的一点补充:为了不使关系加倍(即 1-3 和 3-1),我添加了 where 子句:

select ab1.a as a1, ab2.a as a2, count(*)
from a_b ab1 join
     a_b ab2
     on ab1.b = ab2.b and ab1.a <> ab2.a
     where ab1.a < ab2.a
group by ab1.a, ab2.a
于 2013-09-07T12:06:58.680 回答