M
M
mukolla2012-09-21 15:45:03
MySQL
mukolla, 2012-09-21 15:45:03

mysql query?

Here such a case happened, if there is a table with users:
table members

idname
oneUser1
2User2
3User3
4User4

a user can have several groups, there is a link
table members_teams table
idmember_idteam_id
oneoneone
2one2
322
433
53one

Task: Select all users who are not members of the group, for example team_id = 1 The
decision came immediately
SELECT * FROM Members WHERE id NOT IN (SELECT id FROM members_teams WHERE team_id = 1)

But it seems to me that with large numbers of users this is not at all suitable, perhaps there is some other option for solving this problem.

Answer the question

In order to leave comments, you need to log in

8 answer(s)
M
Melkij, 2012-09-21
@mukolla

Why is there an id field in the link table?

SELECT Members.* FROM Members LEFT JOIN members_teams ON Members.id = members_teams.member_id and team_id = 1 where members_teams.member_id is null

G
Gleb Starkov, 2012-09-21
@colonel

member is not a user, team is not a group

B
blare, 2012-09-21
@blare

SELECT m.id 
FROM members m
LEFT JOIN members_teams mt ON m.id = mt.member_id and mt.team_id = 1
WHERE mt.team_id is null

S
stanishevsky, 2012-09-21
@stanishevsky

I would use an OUTER JOIN because a user who is not a member of any group satisfies the "Not a member of group 1" requirement, however with an inner join these users will not be returned at all.

E
ertaquo, 2012-09-21
@ertaquo

It's better to use JOIN. Something like this:

SELECT Members.* FROM Members LEFT JOIN members_teams ON Members.id = members_teams.member_id WHERE team_id <> 1

S
Sergey Ozeransky, 2012-09-21
@KREGI

select members.id, members.name from members
inner join members_teams on members.id = members_teams.member_id
where members_teams.team_id  NOT IN (1)

In haste, in general, it makes sense to use the JOIN operator

B
blare, 2012-09-21
@blare

SELECT m.id FROM members m LEFT JOIN members_teams mt ON m.id = mt.member_id and mt.team_id = 1 WHERE mt.team_id is null

S
Sergey Volkov, 2012-09-21
@format1981

SELECT m.id, sum(CASE mt.team_id = 1 WHEN TRUE THEN 1 ELSE 0 END) as in_team FROM members m LEFT JOIN members_teams mt ON mt.member_id = m.id GROUP BY m.id
this query will give a table of all users, and for each will be specified in_team (0 - not in a group, 1 - in a group)
use it as a subquery

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question