检查组是否存在mysql查询

时间:2012-03-31 07:26:00

标签: php 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

groupingId = 3 的插入语句将失败,因为groupingId = 2

上已存在5001,5002,5003

我的select语句应该是什么来检查成员是否已经存在于一个组中... 顺便说一句,即时通讯使用PHP

2 个答案:

答案 0 :(得分: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 :(得分: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;

现在你需要将它与组数进行比较。

相关问题