I have 3 MySQL tables (food
, apple
, and orange
).
I want to delete rows from:
apple(idapple, iduser, name)
orange(idornge, iduser, name)
When deleting a row in food(iduser, name)
using one trigger?
Here is my trigger so far:
CREATE TRIGGER `food_before_delete`
AFTER DELETE ON `food`
FOR EACH ROW
DELETE FROM apple, orange
WHERE
apple.iduser=OLD.iduser and
orange.iduser=OLD.iduser
But it won't compile. How can make a trigger that deletes from two tables at once?
The delete statements may require OLD.iduser and not support NEW.iduser. Check your manual.
I forgot the
BEGIN
andEND
blocks in the trigger. And you have to delete from tables sequentially like this:MySQL walkthrough of making a trigger to delete two tables with one trigger:
1. Login:
2. Create some test tables and insert rows:
3. Make the trigger:
4. See the tables exist and all three are populated.
5. Delete from derp
6. See that derp, foo, and bar are empty now:
Something simpler maybe?
No trigger needed.
Delete from two tables at once with a Trigger:
Triggers are used to enforce data integrity in the tables. You can use triggers to delete from any number of tables at once.
Before initializing triggers we need to change the mysql delimiter operator temporarily because triggers use semicolon
;
operator to specify multiple sql commands within the trigger.Step 1 Change current delimiter:
Step 2 Create trigger:
Step 3 Restore previous delimiter:
Explanation:
OLD
is a builtin keyword and refers to the blog table row that we are deleting. Mysql runs the triggerblog_before_delete
whenever we delete an entry in the blog table. I the trigger fails, then the delete is rolled back. This helps ensure Atomicity, Consistency, Isolation, and Durability in our database.