如果存在子记录,则防止删除父记录

Dak*_*h B 0 php mysql sql database

我有一个类别表

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;
Run Code Online (Sandbox Code Playgroud)

这就是它在运行后显示带有子类别的类别的方式

在此处输入图片说明

如果父记录有一个或几个子记录,我需要防止删除父记录。我该怎么做?。

Mar*_*c B 5

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

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;
Run Code Online (Sandbox Code Playgroud)

您必须将其作为单独的alter,因为它不会在表定义本身中工作 - 那时表不存在,因此 FK 验证将失败并且不允许创建表。