Question

I have 2 mysql tables, members and team_members.

members table:

member_id
name

team_members table:

team_id
member_id

I want to select the data from the members table that do not belong to any team (do not exist in team_members table)

                    SELECT *
                    FROM members
                    INNER JOIN team_members
                    ON members.member_id = team_members.member_id

The problem is that the query is doing precisely the opposite i need. It is selecting the data from the members that already have a team. I also tried with '!=' but that gives me all fields duplicated, but does not duplicate the members that belong to a team.

Was it helpful?

Solution 2

Try this:

SELECT *
FROM members a
WHERE NOT EXISTS (
  SELECT 1
  FROM team_members b
  WHERE b.member_id = a.member_id
  )

Notice this syntax follows very closely to how you phrased your question. Sometimes SQL can be very easy; but like any language, you need to master the vocabulary.

OTHER TIPS

Use a left join, and select the records where there is no corresponding data from the team_members table:

select m.*
from members as m
left join team_members as t on m.member_id = t.member_id
where t.member_id is null
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top