I have the following (abridged schema) – 3 tables – user, job, job_type
TABLE: job_type
COLUMN: job_type_id
1
2
TABLE: user
COLUMN: user_id
101
102
103
TABLE: job
COLUMNS: job_id | user_id | job_type_id
4 | 101 | 1
5 | 101 | 2
6 | 102 | 1
7 | 103 | 2
I want to write a query that returns all of the users who have a job in the job table where job_type_id = 1, but if they ALSO have a job with job_type_id = 2, to exclude them from the results. Therefore, the target resultset should return back user 102 only.
You haven’t indicate what DBMS you’re using, but here are some queries that should work in almost any:
Some DBMSes also offer a special
MINUSorEXCEPTfeature that you can use. That would look something like this: