2016-11-01 250 views
-1

1台MySQL查询选择

GroupID MemberID Name 
    1  1  ---  
    1  23  ---  
    2  1  ---  
    2  23  ---  
    2  24  ---  
    3  1  ---  
    3  24  ---  

第二台

ID MemberCount GroupName 
1  2   --- 
2  3   --- 
3  2   --- 

现在我想

select the GroupID where MemberID = (1 and 23) and MemberCount = 2 

我使用MySQL和交叉而我该怎么不能用这样做

+1

'MEMBERID? –

+0

不,它会选择组号为1,2,3的,因为全部有1或23个 –

+0

哦。所以你需要使用这两个ID的用户?然后'基本上在(1,23)有count(memberid)= 2'的地方。 –

回答

2
SELECT a.groupID 
FROM table1 a 
, table2 b 
WHERE b.id = a.groupID 
AND b.MemberCount = 2 
AND a.MemberId in (1,23) 
HAVING COUNT(DISTINCT(MemberId)) >= 2; 
+0

这是回报1,1,3,但我需要1 –

+0

它错了我更新了答案,现在尝试。 –

0

这应该工作...我猜的名字。在(1,23)`

SELECT g.id 
FROM group g 
WHERE g.membercount = 2 
AND EXISTS (SELECT null FROM user_group ug WHERE ug.groupid = g.id AND ug.memberid = 1) 
AND EXISTS (SELECT null FROM user_group ug WHERE ug.groupid = g.id AND ug.memberid = 23) 
0
select GroupID from table1 inner join table2 on table1.GroupID=table2.ID where MemberCount=2 and MemberID in (1,23); 
+0

此查询仅返回1 –

+0

IN运算符采用逗号分隔的值列表,在您的答案中,“1和23”将被视为导致答案1的表达式 - 因此查询的最后部分基本上是“ (1)中的MemberID“。这导致查询返回1和3 - 不只是1. – PaulF

+0

对不起,只是一个简单的错误 –