我有一个复杂版本的问题(How to select columns with same set of values in mysql?)来处理。
在关系R(A,B,C)中,问题是找出“有4个或更多共同B的A”。仅供参考:“AB”是候选键。
我能做的就是这个
查询:
select * from
(select A, group_concat (B separator ', ') all_b's from R group by A having
(count(B))>3) p1
join
(select A, group_concat (B separator ', ') all_b's from R group by A having
(count(B))>3) p2
on p1.all_b's = p2.all_b's and p1.A <> p2.A;
输出:
Null Set
但是,答案应该是别的。 知道怎么处理这个吗?
示例数据:
A B C
a1 b1 asdas
a1 b2 sdvsd
a1 b3 sdfs
a1 b4 evevr
a2 b1 jdjd
a2 b2 dkjlfnv
a2 b3 sdfs
a2 b4 evevr
a2 b5 adfgaf
a3 b1 sdfsdf
预期输出
A A count
a1 a2 4
答案 0 :(得分:2)
应该是这样的:
SELECT
first.A AS first_A,
second.A AS second_A,
COUNT(*) AS countSameBs
FROM
R first
JOIN
R second ON
first.B = second.B AND
first.A != second.A
GROUP BY
first_A, second_A
HAVING
countSameBs >= 4 AND
first_A < second_A