I have a table called Staff and a table called Supervisors.
Staff has StaffID, FirstName, LastName, etc...
Supervisors contains RelationshipID, StaffID, SupervisorID, SetBy, SetOn, Status.
Basically, the Supervisors tables gives us an audit trail for the Staff self-relationship. We have a table of Staff, and we have a table of Staff:Staff relationships (supervisor:staff) with some extra information (obsolete, current, incorrect) and a StaffID who set it and when they set it.
Now, I'm writing a query to find all orphaned staff members. I have:
SELECT *
FROM Staff
WHERE StaffID NOT IN (SELECT StaffID
FROM Supervisors
WHERE Status = 0
OR Status = 2);
(status 0 is initial load from corporate DB and 2 is modified record which has been verified. All others are 'obsolete', 'incorrect', etc...)
The issue is I have over 6000 staff and over 5000 staff:supervisor relationships and this is basically an NxM query meaning MySQL has to sift through 3 million permutations.
I'm not an SQL ninja, is there a better way to do this?
(Note, I do not expect to be running this particular query very often at all)
StaffIdandStatusif you haven't already and watch your query speed drop.