子 - MYsql中的父约束?

时间:2012-02-07 23:58:15

标签: mysql database constraints

我能拥有它们吗?

我有一个约束,如果删除了来自不同表的相关行,则强制删除该行:

node INT UNSIGNED NOT NULL,
id INT UNSIGNED NOT NULL AUTO_INCREMENT,   
name VARCHAR(20) NOT NULL,     
title VARCHAR(200) NOT NULL,
description MEDIUMTEXT,
category VARCHAR(20) NOT NULL,  
parent INT UNSIGNED DEFAULT 0,             # here is the parent term id
                                           # if it's 0 the term has no parent

PRIMARY KEY(id),
UNIQUE KEY(name, node, category),
KEY parent(parent),
KEY category(category),

CONSTRAINT terms FOREIGN KEY(node)
    REFERENCES nodes(id) ON DELETE CASCADE ON UPDATE RESTRICT

如果删除“父”字词,我想要另一个强制自动删除行的约束吗? (如果有一个术语父集)

示例:

node  |  id  |  name  | title   | description    | category | parent
___________________________________________________________________
534   |    1 |  A     | Foooooo | Bla bla...     | A        | 0 
54    |    2 |  B     | Foooooo | Bla bla...     | A        | 1
45    |    3 |  C     | Foooooo | Bla bla...     | A        | 2
545   |    4 |  D     | Foooooo | Bla bla...     | A        | 2
534   |    5 |  E     | Foooooo | Bla bla...     | A        | 1

所以术语如下:

  A
  - B
  --- C
  --- D
  - E

所以如果我删除B,我也希望删除C和D, 如果删除A,则应删除B,C,D,E ......

2 个答案:

答案 0 :(得分:3)

没有“条件”约束这样的东西:你的父字段 allways 引用另一行(即不允许0),或者根本没有约束。

这是一个非常正常的用例,通常你会在父对象上使用ON DELETE TRIGGER解决它,它也删除子节点,由父节点选择它们。

在您的示例中,您可能会考虑类似

的内容
CREATE TRIGGER cascade_delete_children 
    BEFORE DELETE ON node 
    FOR EACH ROW 
         DELETE FROM node WHERE parent=OLD.id;

答案 1 :(得分:2)

您可以使用NULL代替0,并使用级联删除定义FOREIGN KEY

parent INT UNSIGNED NULL DEFAULT NULL,    --- here is the parent term id
                                          --- if it's NULL the term has no parent
...

CONSTRAINT parent_fk FOREIGN KEY(parent)
    REFERENCES thisTable(id) 
        ON DELETE CASCADE 
        ON UPDATE RESTRICT