[英]Check if group exists mysql query
这是我的表结构
分组
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的insert语句将失败,因为groupingId = 2上已存在5001,5002,5003
什么应该是我的选择语句来检查成员是否已经存在于一个组...顺便说一句,我使用PHP为此
你需要这样的东西
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。 如果它什么都不返回,你可以确定它不是重复的。
此查询为每个不同的组提供唯一的字符串
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;
现在您需要将其与组数进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.