2012-03-31 61 views
1

这是我的表结构检查组存在MySQL查询

分组

id groupName 
1 group1 
2 group2 
3 group3 
4 andSoOn 

group_members(正确)

groupingId accountId groupLeader 
1   5001  5001 
1   5002  5001  
2   5001  5001 
2   5002  5001 
2   5003  5001 
3   5001  5001 
3   5002  5001 
3   5003  5001 
3   5004  5001 

这里是我的问题,各组应该是唯一的,以某种方式,成员不应该在一组中相同...

例如:

group_members(错误)

groupingId accountId groupLeader 
1   5001  5001 
1   5002  5001  
2   5001  5001 
2   5002  5001 
2   5003  5001 
3   5001  5001 
3   5002  5001 
3   5003  5001 

与INSERT语句的groupingId = 将失败,因为5001,5002,5003已经存在于groupingId =

what s HOULD是检查我的select语句,如果成员已存在一组... 顺便说一句,使用PHP这个

+0

什么插入会失败? – 2012-03-31 07:35:06

+1

当您插入5001,5002,5003时它会失败,因为它已经存在于groupingId = ** 2 ** – rjmcb 2012-03-31 07:37:08

+0

您的意思是,如果您将一个accountId添加到组中,并且如果其他组具有相同的accountIds ?当有人不希望accountId被插入时。 – riv333 2012-03-31 07:41:11

回答

2

你需要像这样

SELECT groupingId, COUNT(*) AS accounts_present 
FROM group_members 
WHERE accountId IN (5001,5002,5003) 
GROUP BY groupingId 
HAVING accounts_present=3 // 3 here is the number of accounts in the "group", i.e. in the IN clause 

这会传回所有相关accountIds所有groupingIds。如果它没有返回,你可以确定它不是重复的。

1

该查询即时为您提供了独一无二的字符串每个不同组

SELECT GROUP_CONCAT(CONCAT(accountId, ',', groupLeader) SEPARATOR '|') FROM group_members GROUP BY groupingId; 

因此,这将给你不同的组

SELECT count(*) FROM (SELECT DISTINCT GROUP_CONCAT(CONCAT(accountId, ',', groupLeader) SEPARATOR '|') AS unique_string FROM group_members GROUP BY groupingId) AS tmp_table; 

现在,你需要将它与群体的数量比较的数量。