Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all records in table which have no reference in another table

I have a table which is called Document.

Document:

id int
docuid int
doc blob

Then I have two referencing tables

AppRequiredDocuments:

id int
appid int
docid int -> references document -> id

AppDocuments:

id int
appid int
docid int -> references document -> id

I have due to an very old migration orphaned items in the document table which have to references in the other tables. How can I delete only the documents in the document table which are not referenced in AppDocuments or AppRequriedDocuments?

like image 298
STORM Avatar asked Dec 18 '16 11:12

STORM


People also ask

How do you DELETE a record from one table that matches another in SQL?

You may wish to delete records in one table based on values in another table. Since you can't list more than one table in the FROM clause when you are performing a delete, you can use the EXISTS clause.

How do you DELETE a record from one table that matches another in access?

Just open the table in Datasheet view, select the fields (columns) or records (rows) that you want to delete, and then press DELETE.


1 Answers

One approach uses a delete join:

DELETE d
FROM Document d
LEFT JOIN AppRequiredDocuments t1
  ON d.id = t1.docid
LEFT JOIN AppDocuments t2
  ON d.id = t2.docid
WHERE t1.docid IS NULL AND
      t2.docid IS NULL

The logic here is that if a given Document record is not referenced by anything in the two auxiliary tables, then in the result set of the join the docid columns for those two other tables should both be NULL.

like image 86
Tim Biegeleisen Avatar answered Oct 09 '22 20:10

Tim Biegeleisen