Josh Colvin
Josh Colvin

Reputation: 23

Compare and remove rows from a specific table

I am working with a database table that stores, among other things, an AssociateID field and a DocumentName field. The table is used to keep records of which associates are missing which documents.

I am trying to write a stored procedure that will remove a row for 'Restrictive Covenant Letters' if an entry for 'Termination Statement' cannot be found for the same associate. Below is the body of what I have so far:

DELETE from tbl_HR_Auditing_Reports
WHERE DocumentName = 'Restrictive Covenant Letters'
AND NOT EXISTS
    (
        SELECT TS.AssociateID
        FROM
            (SELECT AssociateID FROM tbl_HR_Auditing_Reports WHERE DocumentName = 'Termination Statement (*)') TS,
            (SELECT AssociateID FROM tbl_HR_Auditing_Reports WHERE DocumentName = 'Restrictive Covenant Letters') RCL
        WHERE  TS.AssociateID = RCL.AssociateID
    )

I think I am close, but sql isn't really my forte. If anyone could possibly help, I would really appreciate it!

Upvotes: 2

Views: 82

Answers (1)

GarethD
GarethD

Reputation: 69769

According to the MySQL manual:

Currently, you cannot delete from a table and select from the same table in a subquery.

To get around this you can use a temporary table, inserting the relevant rows into the temporary table, then referencing it in the delete statement.

CREATE TEMPORARY TABLE tmp (AssociateID INT);
INSERT INTO tmp (AssociateID)
SELECT  AssociateID
FROM    tbl_HR_Auditing_Reports
WHERE   DocumentName = 'Termination Statement (*)';

DELETE 
FROM    tbl_HR_Auditing_Reports 
WHERE   DocumentName = 'Restrictive Covenant Letters'
AND     NOT EXISTS
        (   SELECT  1
            FROM    tmp
            WHERE   tmp.AssociateID = tbl_HR_Auditing_Reports.AssociateID
        )

Example on SQL Fiddle

Upvotes: 2

Related Questions