mysql - How to select a user from many-to-many table that is in two groups? -


I really do not need the following question, but I'm awake with this "theoretical problem" that I'm having trouble Are finding out. Say that I have three tables: a user table, group table, and user_group table which are many-to-many, so if a user comes under groups 1 and 2 then there will be two separate rows for each.

Now, assuming that there are many groups, I especially users who are group 2 and both 3, for example?

I tried to do something with these lines, but it was shown blank:

  SELECT * from 'users_groups' GROUP user_id by HAVING group_id = 2 and group_id = 3   

I believe that both groups are in the same line, which will not work clearly, how will I do this?

Edit: How about both forms: Where should the user be in these two groups, and the user should be at least in both of these groups?

  select by user_groups GROUP BY user_id WHERE group_id IN (2,3) HAVING COUNT ( 1) = 2   

It surely assumes that { user_id , group_id } is unique (and there is no other column there Which can add additional rows in the count). Otherwise, you can make it clear: user_id WHERE group_id IN (2,3) HAVING COUNT (DISTINCT group_id) = 2


 < The code> SELECT *> 

only is a bit more complex in these two groups. You can either:

  SELECT * users_groups g1 GROUP by user_id WHERE Group_ID IN (2,3) and no (example 1 as user_groups as G2 ou Where g2.user_id = g1 User_id and group_id IN (2,3)) from hosting COUNT (1) = 2   

<,

  users_groups by G1 group user_id HOSTING COUNT (1) = 2 and SM (In case when Group_ID (2,3) then 1 ELSE 0 END) = 2   

In groups 2 and 3, more than 2 Total with groups:

  Select user_groups g1 to group user user_id is SUM (case when group_id IN (2,3) THEN 1 ELSE 0 END) = 2 and COUNT (1)> 2    

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -