我有一个看起来像的表:
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