[英]Check if group exists mysql query
This is my table structure 这是我的表结构
groupings 分组
id groupName
1 group1
2 group2
3 group3
4 andSoOn
group_members (correct) 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
here's my problem, every group should be unique, in a way that the members should not be the same in a group... 这是我的问题,每个小组都应该是独一无二的,其成员不应该在小组中相同......
for example : 例如 :
group_members (wrong) 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
an insert statement with the groupingId = 3 will fail because 5001,5002,5003 already exists on groupingId = 2 groupingId = 3的insert语句将失败,因为groupingId = 2上已存在5001,5002,5003
what should be my select statement to check if the members already exists in a group... btw, im using PHP for this 什么应该是我的选择语句来检查成员是否已经存在于一个组...顺便说一句,我使用PHP为此
You need something like this 你需要这样的东西
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
This will return all groupingIds that have all the relevant accountIds. 这将返回具有所有相关accountIds的所有groupingIds。 If it returns nothing you can be sure it is not a duplicate. 如果它什么都不返回,你可以确定它不是重复的。
This query gives you unique string for every different group 此查询为每个不同的组提供唯一的字符串
SELECT GROUP_CONCAT(CONCAT(accountId, ',', groupLeader) SEPARATOR '|') FROM group_members GROUP BY groupingId;
So this will give you number of different groups 因此,这将为您提供多个不同的组
SELECT count(*) FROM (SELECT DISTINCT GROUP_CONCAT(CONCAT(accountId, ',', groupLeader) SEPARATOR '|') AS unique_string FROM group_members GROUP BY groupingId) AS tmp_table;
Now you need to compare it with number of groups. 现在您需要将其与组数进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.