Home > Blockchain >  MS ACCESS Query with junction table, for all items in one table, but not in another
MS ACCESS Query with junction table, for all items in one table, but not in another

Time:02-26

To create a many-to-many relationship, I have three tables:

tblEmployee, contains employees

tlkpPermission, contains 11 different possible permission groups an employee can be part of

tblEmployeeXPermission, combines the EmployeeID with one or more PermissionID

What I’m trying to create is a query that shows what permission groups an employee is NOT part of.

So, if EmployeeID 12345 is associated with PermissionID 1,2,3,4,5, but NOT 6,7,8,9,10,11 (in the EmployeeXPermission table) then I want the query to show EmployeeID 12345 is not part of PermissionID 6,7,8,9,10,11.

Of all the JOINs and query options, I can only get a query to show which PermissionIDs an employee is associated with, but not the PermissionIDs the employee is not associated with.

Any help would be appreciated.

Thanks

CodePudding user response:

You need to start with all combinations of employees and permissions, and this type of join is CROSS JOIN, but MsAccess SQL does not have it in the new SQL syntax. You can use the old syntax of listing your tables in the FROM clause, comma separated, and provide the join condition, if any, in the WHERE clause:

SELECT 
  EmployeeId,
  PermissionID
FROM 
     tblEmployee as E,
     tlkpPermission as P
where not exists (
       select 1 
       from tblEmployeeXPermission X 
       where X.EmployeeId=E.EmployeeId 
       and X.PermissionId=P.PermissionId
       )

Here the part up to the WHERE clause would give you all employee - permission combinations, and the WHERE clause removes those occuring in the tblEmployeeXPermission, leaving you with the ones you want.

  • Related