Delete from A where not in B

wxdqz

New Member
Hello!

I have the following problem:
2 tables:

photo: (photo_id, house_id, ...)
house: (house_id, ...)

I would like to DELETE all records FROM photo WHERE photo.house_id does not exist in house. (deleting all photo's of a house when the house has been deleted)

Is this possible in one query?

(I have figured out how to SELECT them, but join does not work in DELETE: "SELECT photo_id FROM photo LEFT JOIN house ON photo.house_id = house.house_id WHERE house.house_id IS NULL"; )

I have worked out a solution for my problem, but maybe any of you experts knows a beter way:
$dbresult = query("SELECT photo_id FROM photo LEFT JOIN house ON photo.house_id = house.house_id WHERE house.house_id IS NULL");
$values = "";
while ($photo = mysql_fetch_row($dbresult)) {
$values .= "$photo[0], ";
}
$values = substr($values, 0, -2);
$dbresult = query("DELETE FROM photo WHERE photo_id IN ($values)");

Anyone? Thanks very much in advance!

Rgards, Maarten
 
Back
Top