我有一个SQL表,它可以引用表中的另一个记录作为其parent,但不应该引用它自己.我曾try 使用CHECK约束来强制执行此操作,但try 失败了,因为id是一个自动递增列.有没有其他方法可以确保parent_id <> id

我当前的try 失败,错误为Check constraint 'not_own_parent' cannot refer to an auto-increment column. (errno 3818):

CREATE TABLE `content` (
    `id` serial PRIMARY KEY NOT NULL,
    `item_id` int NOT NULL,
    `nested_item_id` int,
    `block_id` int,
    `order` int NOT NULL,
        CONSTRAINT not_own_parent CHECK (nested_item_id <> id)
);

推荐答案

下面是使用触发器取消违反您所描述的条件的插入的演示.必须使用AFTER触发器,因为在BEFORE触发器中尚未生成自动增量值.

mysql> delimiter ;;
mysql> create trigger t after insert on content
    -> for each row begin
    -> if NEW.nested_item_id = NEW.id then
    -> signal sqlstate '45000' set message_text = 'content cannot reference itself';
    -> end if;
    -> end;;
mysql> delimiter ;

mysql> insert into content set item_id = 1, nested_item_id = 1, `order` = 1;
ERROR 1644 (45000): content cannot reference itself

mysql> insert into content set item_id = 1, nested_item_id = 2, `order` = 1;
Query OK, 1 row affected (0.01 sec)

Mysql相关问答推荐

如何在逗号分隔字符串值中使用LEFT函数

—符号在哪里条件""

在MySQL中存储一条帖子的点赞数量

MySQL-带有用户定义变量的IF-THEN语句

SQL:如何 Select 每个客户最后购买的产品?

基于多个 where 子句在规范化表中查找公共 ID(值)

使用 autocommit = 0 和 InnoDB 表的 LOCK TABLES 检测死锁

当用它的别名替换 (MAX(s.salary) - MIN(s.salary) 它将不起作用.. 为什么?

如何创建一个判断行是否存在的mysql查询-如果存在我想插入一条新记录,否则增加一个值

如何从将分钟、天、月和年存储在不同列中的表中查询数据

有没有更好的方法在无限滚动的网页上呈现获取的提要数据?

MySQL UPDATE 锁会因为连续的 SHARE 锁而饿死吗?

如何查询打印已售罄的产品? [MYSQL]

Facebook user_id:big_int、int 还是 string?

在 MySQL 的存储过程中调用存储过程

不是唯一的表/别名

docker-entrypoint-initdb 中的 MySQL 脚本未执行

如何在mysql中连接整数(整数和整数)和varchar(nvarchar和varchar)等数据类型?

PDO:MySQL 服务器已消失

MySQL:按字段排序,将空单元格放在末尾