1

I have two tables. I want to draw a sample of the first table except where the person in the first table is also in a second table. Am having trouble doing this seemingly simple query.

table users

id|name

table catuser

id|userid|catid

I have tried

SELECT u.*,c.userid FROM `users` u
LEFT JOIN `catuser` c
ON (u.id = c.userid AND c.userid <> '197')
WHERE u.id = '1'

and variations to no avail. Would appreciate any suggestions.

3 Answers 3

2

How abt. this:

SELECT u.*,c.userid 
FROM `users` u
LEFT JOIN `catuser` c
ON u.id = c.userid 
WHERE u.id = '1'
AND c.userid <> '197'
AND c.userid is null
Sign up to request clarification or add additional context in comments.

Comments

2
SELECT * FROM users WHERE id NOT IN (SELECT DISTINCT userid FROM catuser)

Comments

0

If you want to query only users that have one or more categories, you can use a WHERE EXISTS query:

SELECT u.* FROM `users` u
WHERE EXISTS (SELECT * FROM catuser WHERE catuser.userid = u.id)

Another possibility is to do a left join, and check whether the join succeeded on checking on null:

SELECT u.*, c.* FROM `users` u
LEFT JOIN catuser c ON u.id = c.userid
WHERE c.id IS NOT NULL

If there is no corresponding row in catuser, all catuser fields will be null. By checking whether c.id is not null, you only include the rows with a category.

Note that the join may return a user multiple time, if he is in multiple categories.

Comments

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.