php - Mysql query fetch all rows that matches the user groups is only one -


i have 2 tables in mysql database

1.loc8_users (id,username,password,email,phone)

2.loc8_users_groups (id,user_id,group_id).

here loc8_users_groups store group id's assign each users.

i want fetch rows loc8_users table in user have 1 group

please give try:

select  u.* loc8_users u inner join  (     select      ug.user_id     loc8_users_groups ug     group ug.user_id     having count(distinct ug.group_id) = 1 ) t on u.id = t.user_id 

explanation:

select   ug.user_id loc8_users_groups ug group ug.user_id having count(distinct ug.group_id) = 1; 

this query returns user_ids involved in 1 group.

we got user_ids need user information of user_ids. making inner join between query result , loc8_users table on matching user_id do.


Comments