简体   繁体   中英

SQL Statement - Excluding certain data

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.

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.

select  job
from    job
where   id not in   (select jobId
                    from    jobs)

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 (ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM