Search code examples
sqlms-access

How to find non-existing records?


I have 3 Tables

Table 1 is a Trainings Table:

TrainingID Name Someotherfield
1 aa whatever is
2 bb in this field

Table 2 is an employee list

EmpID LastName FirstName DOB etc.
1 John Doe mm
2 Jane Foe yy

Table 3 is the table where these two tables meet :

EmpID TrainingID Compdate etc
1 3 ddmmyy x
2 1 ddmmyy x
2 2 ddmmyy x
2 3 ddmmyy x

What I need to be able to do, is query these three tables and return an EmpID and a TrainingID that are both not in the third table, so in this example my ideal response would be :

EmpID TrainingID
1 1
1 2

What I have managed to do so far, is not great:

SELECT * 
FROM CompletedTrainings
LEFT JOIN Trainings ON Trainings.TrainingID = CompletedTrainings.Training
WHERE ISNULL ( Trainings.TrainingID

This returns a list of employees, but not the training numbers that are missing.

I have tried a variant of this using NOT EXISTS:

SELECT CompletedTrainings.Employee, CompletedTrainings.Training
FROM CompletedTrainings
WHERE NOT EXISTS (
SELECT TrainingID, [Training Name]
FROM Trainings
WHERE Trainings.TrainingID = CompletedTrainings.Training);

This again returns a list of employee names, but not the names of the missing trainings. How can I do this?


Solution

  • Use a cross join (via ,) in MS Access and then not exists or left join:

    select t.*, e.*
    from trainings as t,
         employees as e
    where not exists (select 1
                      from employeeTrainings as et
                      where et.EmpID = e.EmpID and et.trainingID = t.trainingID
                     );