Php 当父行链接到子行时

Php 当父行链接到子行时,php,mysql,sql,Php,Mysql,Sql,示例:我有一个类别表,其外键指向同一个表: CREATE TABLE `categories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(250) COLLATE utf8_unicode_ci NOT NULL, `parent_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`parent_i

示例:我有一个类别表,其外键指向同一个表:

 CREATE TABLE `categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
`parent_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `categories` (`id`)
)
如何约束父id,使其不能是子父id

例如: 我们有一个父行,其中父id等于子id:

['1', 'parent_name', '**2**']
子行:

['2', 'child_name', '**1**']

如何通过MySQL解决此问题?

在插入过程中(根据表的定义),您在parent\u idid上有外键。您的示例是一个悖论,但它可能发生在表的更新期间,因此您需要为更新创建触发器,以防止更新表,例如,在这种情况下,
检查
约束不起作用,正如我提到的,一种方法是在更新之前为
使用
触发器

CREATE TRIGGER trigger_categories
BEFORE Update
   ON categories FOR EACH ROW

BEGIN
    DECLARE msg VARCHAR(255);
    IF EXISTS (select * from categories c where c.id=NEW.parent_id and c.parent_id=NEW.id) THEN
       set msg = "DIE: you can not make a parent of chield as it's chield...";
       SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = msg;
       // also you can make NEW as NULL for preventing update under mentioned condition
    END IF;    
END;

您基本上是在有向图中检测循环。SQL在这方面是一种非常糟糕的语言。考虑另一种语言,也许是PHP本身。我不知道如何在不单独查看现有记录的情况下修复现有的记录。