user1162628
user1162628

Reputation: 81

Query where a number is not in a column?

I have an sql database with a table holding users(UserID, Name), a table holding events(EventID, EventName), a table holding roles(RoleID, RoleName) and a table assigning roles to users for each event (assignID, EventID, UserID, RoleID).

Now I wanna get a list of all the events that do not contain a certain role, say every event without the roleID 1, but I don't want any rows with a different roleID. how would I do that?

Upvotes: 0

Views: 108

Answers (1)

stryba
stryba

Reputation: 2028

Something like this should do

SELECT * 
FROM events 
WHERE eventid NOT IN 
     (SELECT eventid FROM assign WHERE roleID=1)

Or if subqueries are not available

SELECT e.* 
FROM events e 
  LEFT JOIN assign a ON (e.eventid=a.eventid AND a.roleid=1) 
WHERE a.roleid IS NULL

One more equivalent query:

SELECT * 
FROM events e 
WHERE NOT EXISTS
     (SELECT * FROM assign a WHERE a.eventid=e.eventid AND roleID=1)

Upvotes: 4

Related Questions