簡體   English   中英

檢查組是否存在mysql查詢

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM