Reputation: 185
I'm still in the learning phase of SQL statements and I'm hoping someone out there can help.
I have a many-to-many database base relationship.
The table Department can have multiple Jobs associated with it and and Jobs can be related to multiple Departments. So I have this basic relationship type.
Job.ID (one-to-many) Jobs.JobID
Jobs.DepartmentID (many-to-one) Department.ID
What I'm trying to do is get a list of Jobs that aren't already associated with a department.
tbl=Job
ID Job Active
1 10-3242 Yes
2 12-3902 Yes
3 12-3898 Yes
tbl=Jobs
ID DepartmentID JobID
1 3 1
2 3 2
tbl=Department
ID Department
1 Administration
2 Sales
3 Production
Query:
string sql = "SELECT Job FROM (Job " +
"INNER JOIN Jobs ON Job.ID = Jobs.JobID) " +
"INNER JOIN Department ON Jobs.DepartmentID = Department.ID " +
"WHERE Department.Department <> 'Production'";
I'm expecting the job code 12-3898
to be returned but obviously I'm forgetting something.
Any assistance would be great. Cheers.
Upvotes: 3
Views: 2234
Reputation: 395
Unfortunately, I'm not in an environment where I can test the results. However the basic thought process behind this is whenever you want to return rows from a table that do NOT have a matching row from another table, you have to do an outer join. The intention being you want to display ALL the rows from the job table (i.e. left outer join). However you want to filter where the departmentID IS NULL, because the NULL departmentID will be the row in the job table with no matching departmentID from the department table. Hope that helps.
SELECT j.id, j.job, j.active, jd.departmentid
FROM job j
LEFT OUTER JOIN jobs jd ON j.id = jd.jobid
LEFT OUTER JOIN department d ON d.id = jd.departmentid
WHERE jd.departmentid IS NULL
Upvotes: 0
Reputation: 8170
You can use a LEFT JOIN
. The LEFT JOIN
keyword returns all rows from the left table with the matching rows in the right table. The result is NULL
in the right side if there is no match. Since you want the jobs without a matching department, you can check if the joined DepartmentID
is NULL
:
SELECT Job.Job
FROM Job LEFT JOIN Jobs ON Job.ID = Jobs.JobID
WHERE Jobs.DepartmentID IS NULL;
Checkout this demo. Let me know if it works.
Upvotes: 2
Reputation: 1117
select job
from job
where id not in (select jobId
from jobs)
Upvotes: 0