Answer the question
In order to leave comments, you need to log in
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
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;
Are joins really needed here? Like it is possible through normal where from?
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 групп через ,')
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question