Search code examples
sqljoinsql-delete

SQL Delete based on condition in join


It is possible to delete records based on a satisfied condition with a join query?

For instance, I have a linking table joining 3 records. The query I have at the moment deletes records from this table where one of the id's isn't IN() an imploded Php array. I've come to realise that the query should only remove records from this table if the id's don't exist in the array and they belong to a certain other table based on the a link to another table.


Solution

  • I like to use EXISTS clauses for this:

    DELETE FROM TableA
    WHERE
      <<put your array condition here>> 
      AND NOT EXISTS 
      (SELECT 1 FROM TableB Where TableB.ID=TableA.ID)