从下面的相册表中,我需要提取至少3个musician_ids匹配的album_ids,例如:预期的结果是 100 和 102 ,因为它们都包含musician_ids 2,3和4。
id album_id musician_id
1 100 1
2 100 2
3 100 3
4 100 4
5 101 3
6 101 4
7 101 5
8 101 6
9 102 2
10 102 3
11 102 4
12 102 7
13 103 1
14 103 2
15 103 8
16 103 9
使用MySQL Workbench。感谢所有的帮助!感谢。
答案 0 :(得分:1)
试试这个
SELECT
`album_id`, COUNT(`album_id`) AS `count`
FROM
albums
GROUP BY
`album_id`
HAVING
`count` >= 3
答案 1 :(得分:0)
这是一套内置问题。这是一个典型的解决方案:
select album_id
from albums
where musician_id in (2, 3, 4)
group by album_id
having count(distinct musician_id) = 3;
编辑:
你修改过的问题似乎与原文有很大不同,但我可以看出歧义在哪里。
答案是:
select a1.album_id, a2.album_id, count(*) as nummatches,
group_concat(a1.musician_id) as musicians
from albums a1 join
albums a2
on a1.musician_id = a2.musician_id and a1.album_id < a2.album_id
group by a1.album_id, a2.album_id
having count(*) >= 3;