简体   繁体   English

子-MYsql中的父约束?

[英]Child - parent contraints in MYsql?

Can I have them? 能给我吗?

I have a constraint that forces delete of the row if a related row from a different table is deleted: 我有一个约束,如果从另一个表中删除相关行,则强制删除该行:

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

I want another constraint that forces auto-delete of the row if the "parent" term is deleted? 我想要另一个约束,如果“父”项被删除,该约束会强制自动删除该行? (if there is a term parent set) (如果有术语父集)

Example: 例:

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

so terms look like: 所以术语看起来像:

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

So if I delete B, I want C and D to be deleted as well, if I delete A, then B, C, D, E should be deleted... 因此,如果我删除B,我也希望删除C和D,如果我删除A,则应该删除B,C,D,E ...

There is no such thing as a "conditional" constraint: Either your parent field allways references another row (ie no 0 allowed), or it is no constraint at all. 没有“条件”约束这样的东西:要么您的父字段始终引用另一行(即不允许0),要么根本就没有约束。

This is quite a normal usecase, typically you would work around it with an ON DELETE TRIGGER on the parent, that also deletes the children, selecting them by parent. 这是一个很正常的用例,通常您会在父级上使用ON DELETE TRIGGER解决该问题,该操作也会删除子级,并按父级选择它们。

In your example you might consider something like 在您的示例中,您可能会考虑类似

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

You can use NULL instead of 0 and define the FOREIGN KEY with cascading deletes: 您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM