I would like to start with assumptions.
- You have a chainlike data model:
Projects --* ProjectSchemes --* Schemes
- Your target is to have only valid chains, so no ProjectSchemes without Project, no Schemes without ProjectSchemes.
- NULL is not a valid value for one of your ids.
- All ids are unique in their table
- You don't use referential integrity mechanisms of your database
As a result your SELECT would list the scheme_id for all Schemes in the Schemes table.
Said that, you should start to delete all ProjectSchemes without a corresponding Project. These are ProjectSchemes with an id of NULL or an id which does not exists in the Projects Table:
DELETE ProjectSchemes WHERE (Project_Id is NULL) OR
(NOT EXISTS (SELECT * FROM Projects WHERE
Projects.Project_Id = ProjectSchemes.Project_Id))
After deleting the ProjectsSchemes without a Project we now may have some new orphans in the Schemes Table. The next thing is now to delete all Schemes which have an id of NULL or an id which does not exists in the ProjectsSchemes Table:
DELETE Schemes WHERE (Scheme_Id is NULL) OR
(NOT EXISTS (SELECT * FROM ProjectSchemes WHERE
ProjectSchemes.Scheme_Id = Schemes.Scheme_Id))
There is still a chance to have schemes which are not connected to a project without deleting the ProjectSchemes.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…