MySQL Trigger:删除间接关联的条目

时间:2014-12-22 16:37:50

标签: mysql sqlite triggers

1作者可以有很多书/ 1本书可以有很多作者

enter image description here

作者被删除时,如何触发MySQL(SQLite)删除图书,其作者只是作者上唯一被删除的图书强>,所以如果没有与之相关的作者,它就不会有书?

示例:

BOOK1: John & Paul
BOOK2: John
BOOK3: Lucy
BOOK4: John & Lucy

如果我从作者中删除john,则触发器将仅删除BOOK2。

authors_books'都是外键:ON DELETE CASCADE

2 个答案:

答案 0 :(得分:0)

如果您需要纯trigger解决方案,请考虑以下

mysql> create table authors (author_id int , name varchar(100));
Query OK, 0 rows affected (0.13 sec)

mysql> create table books (book_id int, title varchar(100));
Query OK, 0 rows affected (0.17 sec)

mysql> create table authors_books (fk_author_id int,fk_book_id int);
Query OK, 0 rows affected (0.13 sec)

mysql> insert into authors values (1,'A'),(2,'B'),(3,'C');
Query OK, 3 rows affected (0.05 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> insert into books values (1,'book1'),(2,'book2'),(3,'book3'),(4,'book4');
Query OK, 4 rows affected (0.04 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> insert into authors_books values (1,1),(2,1),(3,2),(1,3),(1,4),(3,4);
Query OK, 6 rows affected (0.04 sec)
Records: 6  Duplicates: 0  Warnings: 0

让我们现在写下触发器

delimiter //
create trigger auth_delete after delete on authors
for each row
begin
 delete b from books b 
 join authors_books ab on ab.fk_book_id = b.book_id 
 where ab.fk_author_id = old.author_id 
 and not exists (
   select 1 from authors_books ab1 
   where b.book_id = ab1.fk_book_id 
   and ab1.fk_author_id <> ab.fk_author_id
  );

  delete from authors_books where fk_author_id = old.author_id ;
end;//

delimiter ;

在上面的代码中,我也删除了要删除的作者的行authors_books

测试::

mysql> delete from authors where author_id = 1 ;
Query OK, 1 row affected (0.05 sec)

mysql> select * from authors_books ;
+--------------+------------+
| fk_author_id | fk_book_id |
+--------------+------------+
|            2 |          1 |
|            3 |          2 |
|            3 |          4 |
+--------------+------------+
3 rows in set (0.00 sec)

mysql> select * from books ;
+---------+-------+
| book_id | title |
+---------+-------+
|       1 | book1 |
|       2 | book2 |
|       4 | book4 |
+---------+-------+
3 rows in set (0.00 sec)

答案 1 :(得分:0)

我写了这个简单的触发器。完美运作:

PRAGMA primary_keys = ON;
PRAGMA foreign_keys = ON;

CREATE TRIGGER DEL_BOOKS BEFORE DELETE ON authors_books
WHEN

 (SELECT COUNT(*) FROM authors_books WHERE
  fk_book_id = OLD.fk_book_id AND fk_author_id != OLD.fk_author_id) = 0 

BEGIN

  DELETE FROM books WHERE books.book_id = OLD.fk_book_id;

END;