How to Delete Records NOT IN

后端 未结 3 1030
后悔当初
后悔当初 2020-12-17 17:57

Hi I have the following SQL Query which gives me Scheme_Id which exist both in ProjectSchemes and Schemes table. I want to

相关标签:
3条回答
  • 2020-12-17 18:10
    DELETE FROM schemes
    WHERE scheme_id NOT IN (
        SELECT DISTINCT scheme_id
        FROM projectschemes
        WHERE scheme_id IS NOT NULL
    )
    

    Or you can alternatively use

    DELETE
    FROM schemes
    WHERE NOT EXISTS (
          SELECT 1
            FROM projectschemes
           WHERE projectschemes.scheme_id = schemes.ID
          )
    
    0 讨论(0)
  • 2020-12-17 18:16

    I would like to start with assumptions.

    1. You have a chainlike data model: Projects --* ProjectSchemes --* Schemes
    2. Your target is to have only valid chains, so no ProjectSchemes without Project, no Schemes without ProjectSchemes.
    3. NULL is not a valid value for one of your ids.
    4. All ids are unique in their table
    5. 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.

    0 讨论(0)
  • 2020-12-17 18:17
    DELETE s
    FROM Schemes s LEFT JOIN ProjectSchemes ps ON s.Scheme_Id=ps.Scheme_Id
    WHERE ps.Scheme_Id IS NULL
    

    But sounds like you need this

    DELETE sp
    FROM ProjectSchemes sp LEFT JOIN Schemes s ON sp.Scheme_Id=s.Scheme_Id
    WHERE s.Scheme_Id IS NULL
    
    0 讨论(0)
提交回复
热议问题