D
D
dj_vadim2015-11-19 22:58:20
MySQL
dj_vadim, 2015-11-19 22:58:20

MySQL many-to-many selection (groups of users)?

I have three tables:
users_list(user_id, name, uid, gender) -- users
groups_list(group_id, uid, title) -- groups
users_groups (id, group, user_id) -- a bunch of users with groups. One user can belong to several groups
I can't build a select query. I need to select all users from two, three or more groups. So that they do not repeat. The uid of the groups is set and users are selected based on them.
Tried like this:
SELECT ul.user_id, ul.name, ul.uid, ul.gender
FROM users_list ul
INNER JOIN users_groups ON ul.user_id=users_groups.user_id
LEFT JOIN groups_list ON groups_list.group_id=users_groups.user_id
WHERE groups_list.uid=1233334555 ;
But something does not cook the pot)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2015-11-20
@dj_vadim

SELECT `ul`.`user_id`, `ul`.`name`, `ul`.`uid`, `ul`.`gender`
    FROM `users_list` AS `ul`
    JOIN `users_groups` AS `ug` ON `ul`.`user_id` = `ug`.`user_id`
    JOIN `groups_list` AS `gl` ON `gl`.`group_id` = `ug`.`user_id`
    WHERE `gl`.`uid` = :gid;

In general, your database is built incorrectly - unnecessary artificial keys are entered in the tables in the presence of natural ones. After normalization, the following will remain:
user(uid, name, gender), unique(uid)
group(gid, title), unique(gid)
user_group(gid, uid), unique(gid, uid)

I
Ivan, 2015-11-19
@LiguidCool

Are joins really needed here? Like it is possible through normal where from?

W
wellgo, 2015-11-19
@wellgo

I did not understand why you need groups_list if there is already a connection by user_id?

SELECT t1.* 
FROM users_list 
WHERE EXISTS(
   SELECT t2.id 
   FROM users_groups t2 
   WHERE t2.user_id = t1.id AND FIND_IN_SET(t2.id, '1,2,3,4,и другие id групп через ,')
)

Well, or any other check, this is the option "on the task"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question