2016-07-29 52 views
-1

我有一个栏目表防止缺失父母的如果存在子记录

CREATE TABLE `tbl_categories` (
    `id` int(11) NOT NULL, 
    `name` varchar(100) NOT NULL DEFAULT '0', 
    `parent_id` int(11) NOT NULL DEFAULT '0' 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

,这是它如何显示与子类别的类别,并且运行后

enter image description here

我需要防止的缺失父记录是否有一个或几个子记录。我该怎么做?。

+1

为什么不是外键? – berty

+0

@berty,我在哪里添加外键? –

+0

查看@Marc B回答;) – berty

回答

4

你可以有一个自引用外键,但你必须在两个阶段来创建它:

create table foo (
    id int not null auto_increment primary key, 
    parent int default null 
); 

alter table foo add foreign key (parent) references foo (id) 
    on delete restrict; 

你必须做它作为一个独立的alter,因为它不会在表内工作定义本身 - 该表在该点不存在,因此FK验证将失败并且不允许创建表。

+0

谢谢,那是我一直在寻找的“自我指涉外键”。我不确定是否可以定义一个自引用外键。让我尝试。 –