如何计算postgresql中的多对多关系

时间:2013-09-07 11:36:54

标签: sql postgresql many-to-many cross-join

我有一张表格如下:

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

 1 | b
 3 | b

 2 | c
 3 | c

它表示多对多关系a a -b。 我希望将所有现有关系设为< - > 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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