There is a table tbl_user_groups with fields of the form user_id, group_id. There are a lot of groups.

Records of the form (example): user_id=2, group_id=3 user_id=4, group_id=8 user_id=2, group_id=7 user_id=8, group_id=3 user_id=6, group_id=8 user_id=1, group_id=4 selection of those user_id, which consist in all selected groups from the set, but in others they should not consist (which are not from the list).

Something like SELECT user_id FROM tbl_user_groups WHERE group_id in (3,4,7,8) GROUP BY user_id // Но нужно ещё, чтобы такой пользователь (user_id) не был (не состоял) участником групп, кроме тех, которые перечислены

How to do it? Thank!

  • @Bald shows only those users who are in only one group. And it is necessary for those who consist in any number of groups from the list, but not in others. If I understand the question correctly. - Sergey Gornostaev
  • @SergeyGornostaev I understood the question a little differently, just in case I think I should ask the vehicle to clarify this point - Bald
  • @Sergey Gornostaev, you understood absolutely true! - Robert

2 answers 2

 select distinct user_id from tbl_user_groups where group_id in (3, 4, 7, 8) and user_id not in ( select user_id from tbl_user_groups where group_id in ( select group_id from groups where group_id not in (3, 4, 7, 8) ) ); 
  • Super! Just what was required. Thanks you! - Robert
 SELECT user_id FROM tbl_user_groups WHERE group_id in (3,4,7,8) GROUP BY user_id having count(*) = 4