Emir
Emir

Reputation:

mysql delete operation

is there a way to delete a relation only if it exists in the table? If not, Whats the best approach when deleting a relation in a table:

  1. Check if the relation exists. If it does then delete. (2 operations)
  2. Delete and catch the error if it didnt exist. (1 operation)

Thanks

Upvotes: 0

Views: 303

Answers (3)

vava
vava

Reputation: 25371

DELETE FROM table WHERE id=30

will delete a row if it exists and will do nothing if it is not. No need for catching errors.

Upvotes: 4

arno
arno

Reputation: 357

DELETE deletes a row only if it's exist. It doesn't throw an error if there is nothing to delete.

Upvotes: 1

Staelen
Staelen

Reputation: 7841

I think you can do a subselect and choose which record you want to delete from that subselect, something like this

DELETE FROM target WHERE target_table.id IN (
  SELECT target_table.id INNER JOIN relation_table ON relation_table.target_table_id = target_table.id
)

where the subselect, using INNER JOIN will return records with relations =)

hope it helps! =)

Upvotes: 0

Related Questions