3

我目前正在制作一个关于主外键关系的表格......

                       book table                    

                bookid     bookname         author
                 0         No book           no author
                 1         Engg Maths        Greiwal
                 2         Java Basics       James Gosling
                 3         Mahabharata       Ved Vyasa
                 4         Ramayana          Valmiki
                 5         Harry Potter      JK Rowling




                        usertable

               userid       name           bookid
                1          Arjun             2
                2          Charles           2
                3          Babbage           3

这里 bookid 是 usertable 中的外键,也是 booktable 中的主键......现在我听说了级联、 setnull 、restrict 和无操作约束......

0 设置为 usertable 中 bookid 列的默认值.....

Now i want a situation when a bookid(primary) entry is deleted from the main table i.e booktable, the entires containing bookid in the user table should be updated to the default value ( i.e here 0 ).....

有没有什么方法……???

我只能说我正在研究 phpmyadmin mysql innodb ......

4

2 回答 2

2

没有内置的方法,但是有一种解决方法。您可以使用 DELETE 触发器来完成此操作:

DELIMITER $$
CREATE TRIGGER `book_delete` BEFORE DELETE ON `booktable`
  FOR EACH ROW BEGIN
    UPDATE `usertable` SET `bookid` = 0 WHERE `bookid` = OLD.`bookid`;
  END $$
DELIMITER ;

但是,请注意 0 不为空,因此如果您对 usertalbe 有任何参照完整性约束(也就是说,如果您将 bookid 设置为 FOREIGN KEY 列),这将引发错误。

作为最佳实践,您确实应该使用 NULL 来表示 usertable 中的行在 booktable 中没有相应的行。

于 2012-07-01T21:30:26.680 回答
1

使用 MySQL,您可以ON DELETE SET NULL在外键上使用。

例如:

CREATE TABLE t1 (
 id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
 title VARCHAR(256)
) ENGINE=InnoDB;

CREATE TABLE t2 (
 id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
 parent_id INT UNSIGNED, 
 INDEX(parent_id),
 FOREIGN KEY (parent_id) REFERENCES t1(id) ON DELETE SET NULL
) ENGINE=InnoDB;

insert into t2 values (null, 3);
insert into t2 values (null, 2);

这将导致表格t2如下所示:

+----+-----------+
| id | parent_id |
+----+-----------+
|  2 |         2 |
|  1 |         3 |
+----+-----------+

删除一行t1如下:

delete from t1 where id = 2;

将导致:

+----+-----------+
| id | parent_id |
+----+-----------+
|  2 |      NULL |
|  1 |         3 |
+----+-----------+

有趣的是,MySQL 会解析一个ON DELETE SET DEFAULT子句——但创建表会失败。

所以简短的回答 - 您可以设置为NULL删除 - 但目前无法设置删除列的默认值并维护外键约束。

于 2012-07-01T21:40:48.660 回答