假设表
team: id, title
team_user: id_team, id_user
我想选择只有指定成员的团队。在这个例子中,我想要团队,其中唯一的用户是id为1和5的用户,没有其他用户。我提出了这个SQL,但对于这么简单的任务来说似乎有点过分。
SELECT team.*, COUNT(`team_user`.id_user) AS cnt
FROM `team`
JOIN `team_user` user0 ON `user0`.id_team = `team`.id AND `user0`.id_user = 1
JOIN `team_user` user1 ON `user1`.id_team = `team`.id AND `user1`.id_user = 5
JOIN `team_user` ON `team_user`.id_team = `team`.id
GROUP BY `team`.id
HAVING cnt = 2
编辑:谢谢大家的帮助。如果您想真正尝试您的想法,可以使用示例数据库结构和数据:http://down.lipe.cz/team_members.sql
答案 0 :(得分:3)
怎么样
SELECT *
FROM team t
JOIN team_user tu ON (tu.id_team = t.id)
GROUP BY t.id
HAVING (SUM(tu.id_user IN (1,5)) = 2) AND (SUM(tu.id_user NOT IN (1,5)) = 0)
我在team_user(id_team,id_user)上假设一个唯一索引。
答案 1 :(得分:1)
您可以使用
SELECT
DISTINCT id,
COUNT(tu.id_user) as cnt
FROM
team t
JOIN team_user tu ON ( tu.id_team = t.id )
GROUP BY
t.id
HAVING
count(tu.user_id) = count( CASE WHEN tu.user_id = 1 or tu.user_id = 5 THEN 1 ELSE 0 END )
AND cnt = 2
不确定为什么您需要cnt = 2
条件,该查询只会获得所有用户ID
1 or 5
答案 2 :(得分:0)
试试这个
SELECT team.*, COUNT(`team_user`.id_user) AS cnt FROM `team`
JOIN `team_user` ON `team_user`.id_team = `team`.id
where `team_user`.id_user IN (1,5)
GROUP BY `team`.id
HAVING cnt = 2