views:

32

answers:

1

I have this piece of logic I would like to implement as a trigger, but I have no idea how to do it! I want to create a trigger that, when a row is deleted, it checks to see if the value of one of its columns exists in another table, and if it does, it should also perform a delete on another table based on another column.

So say we had a table Foo that has columns Bar, Baz. This is what id be doing if i did not use a trigger:

function deleteFromFooTable(FooId)
{
  SELECT (Bar,Baz) FROM FooTable WHERE id=FooId
  if not-empty(SELECT * FROM BazTable WHERE id=BazId)
    DELETE FROM BarTable WHERE id=BarId

  DELETE FROM FooTable WHERE id=FooId

}

I jumped some hoops in that pseudo code, but i hope you all get where im going. It seems what i would need is a way to do conditionals and to loop(in case of multiple row deletes?) in the trigger statement. So far, I haven't been able to find anything. Is this not possible, or is this bad practice? Thanks!

+2  A: 

If you do not have Foreign Key relationships setup between these tables, you need to do that. I will show you the command for setting up what you want when you create the table. Clearly, you will just need to update the table.

CREATE TABLE foo (id INT, bar_id INT,
    FOREIGN KEY (bar_id) REFERENCES bar(id)
        ON DELETE CASCADE
) ENGINE=INNODB;

This will delete any "orphans" when a Foo record is deleted.

Kevin Crowell
thanks kevin, this almost does what i need, except whether or not i delete it depends on whether it is referenced by another table. How would i do that?
Ying
@Ying That is what this should do. It will only delete something if it is not referenced by another table.
Kevin Crowell