Jean Alesi
Jean Alesi

Reputation: 165

Left outer join with multiple conditions - MYSQL

I'm running into some problems with a very simple query. I figure that it must be because of an incorrect assumption about how SQL queries work. I'm trying to write a simple LEFT OUTER JOIN query using the following tables:

tmtrip_viewer( tmtrip_id, tmuser_id )      -> FKs: (tmtrip.id, tmuser.id)
Values: ( 6, 2 )
        ( 6, 3 )
        ( 7, 4 )

tmtrip( id, ...)
Values: (1, ...)
        (2, ...)
        (3, ...)
        (4, ...)

tmuser(id, username, ...)
Values: (1, user1)
        (2, user2)
        (3, user3)
        (4, user4)

What I want to do is: Display alls id from tmuser table given the following conditions: - That the id != '1' - That the id is NOT in table tmtrip_viewer where tmtrip_viewer.tmtrip_id = 7.

Basically, I want to get all the users that are not viewing the tmtrip with tmtrip_id = 7 (except the logged in user ..id='1').

I have formulated the following query, but it does not behave as desired:

SELECT a.`id`, a.`username` FROM 
`tmuser` a LEFT OUTER JOIN `tmtrip_viewer` b
ON a.`id` = b.`tmuser_id` AND b.`tmtrip_id` = '7'
WHERE a.id <> '1'

Why is this not working? What would be the right way to do this?

Upvotes: 0

Views: 1327

Answers (2)

Jim
Jim

Reputation: 6881

I think this should do what you want.

It would show one record for each user that doesn't have ID = 1 and also doesn't have a record in tm_tripviewer with tmtrip_id = 7.

SELECT id, username
FROM tmuser
WHERE id != 1
AND id NOT IN
(SELECT id FROM tmtrip_viewer WHERE tmtrip_id = 7)

Upvotes: 0

Uueerdo
Uueerdo

Reputation: 15941

Add AND b.tmtrip_id IS NULL to your WHERE. Your query is getting all tmusers and their "trip 7" info if they have any; this will reduce the results to only the ones that had no "trip 7" info.

Upvotes: 2

Related Questions