0

I'm looking to join a 2 tables but the second table has a one to many relation. Can I omit the entire row if any of the lines have a certain value? Let me explain more.

User table

id name email
1  bob  [email protected]
2  foo  [email protected]


Music table

id userId
1  1
1  2
2  1
3  1
2  2

Say I don't want it to show the user if he has a relation to music table id 2. Also looking for distinct user.

If I try something like this it will still show both users.

SELECT * FROM users u LEFT JOIN music m ON u.id = m.userId WHERE m.id <> 3

I want it to check all the rows and if it has the id 3, it won't show. I hope I made sense. Thanks a lot.

5
  • Have you tried adding it to your ON condition? ON u.id=muserId and m.id <> 1 Commented Nov 28, 2012 at 3:01
  • I just did but it's returning the same set. But I appreciate the suggestion. Commented Nov 28, 2012 at 3:06
  • 1
    Your query should return only 1 row with user foo so where's the problem? Commented Nov 28, 2012 at 3:12
  • @SubRed Sorry about that but the table might not have been clear. I adjusted that. See right now if I don't want to join the user if he has a music id of 3, it will still show up because he has an id of 1 and 2. Commented Nov 28, 2012 at 3:17
  • Oh I see try my answer below. Is it what you need? Commented Nov 28, 2012 at 3:25

1 Answer 1

1

Try using sub query like this:

SELECT * FROM users
WHERE id NOT IN (SELECT userId FROM music WHERE id=3)

This query means to select all users if their id is not related with music.id 3.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Sorry for the late response, my query was a little bit more complicated than this so I was trying to match it but it worked perfectly. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.