我的表“会员”有字段ID,UserID,GroupID 我想只选择每个成员的成员数超过1的GroupID,如下所示:
ID UserID GroupID
1 1 1 /* we are selecting groups for guy with ID 1, here are 3 people */
2 2 1
3 3 1
4 1 2 /* here the guy is alone in group, ignore him! */
5 1 3 /* select this one too for guy 1, because #members>1 */
6 2 3
对ID为1的家伙进行团体选择,包括同一组中必须至少有2个人,所以这将返回:1,3
但我不知道如何在SQL中执行此操作,我想做类似的事情,但是,它显然不起作用:
SELECT GroupID
FROM Members
WHERE UserID=1
AND COUNT(
SELECT UserID FROM Members WHERE GroupID=**currently iterated group**
)>1;
有可能吗?
答案 0 :(得分:1)
如果我理解正确,您希望组中至少有两个成员,其中一个成员userid = 1
。以下查询使用group by
和having
select m.groupId
from Members m
group by m.groupId
having count(*) > 1 and
sum(case when m.userid = 1 then 1 else 0 end) > 0;
答案 1 :(得分:1)
这将返回具有多个成员的组,用户1是其成员:
select groupid
from members
where groupid in (select groupid from members where userid = 1)
group by groupid having count(*) > 1;
@GordonLinoff提供的解决方案可能更好(效率更高)。