提问者:小点点

MySQL-无法添加或更新子行


mysql版本15.1 Distrib 10.1.44-MariaDB,用于debian-linux-gnu(x86_64),使用readline 5.2

第8613行出现错误1452(23000):无法添加或更新子行:外键约束失败

第8613行:插入puffle_item(id,parent_id,name,type,play_external,cost,quantity,member,food_effect,rest_effect,play_effect,clean_effect)值

它所指的表:

DROP TABLE IF EXISTS puffle_item;
CREATE TABLE puffle_item (
  id INT NOT NULL,
  parent_id INT NOT NULL,
  name VARCHAR(50) NOT NULL DEFAULT '',
  type VARCHAR(10) NOT NULL DEFAULT 'care',
  play_external VARCHAR (10) NOT NULL DEFAULT 'none',
  cost INT NOT NULL DEFAULT 0,
  quantity SMALLINT NOT NULL DEFAULT 1,
  member BOOLEAN NOT NULL DEFAULT FALSE,
  food_effect SMALLINT NOT NULL DEFAULT 0,
  rest_effect SMALLINT NOT NULL DEFAULT 0,
  play_effect SMALLINT NOT NULL DEFAULT 0,
  clean_effect SMALLINT NOT NULL DEFAULT 0,
  PRIMARY KEY (id),
  CONSTRAINT puffle_item_ibfk_1 FOREIGN KEY (parent_id) REFERENCES puffle_item (id) ON DELETE CASCADE ON UPDATE CASCADE
);

尝试放入表中的项目示例:(1,1,'brush','care','none',0,1,FALSE,-2,-2,5,5),

有人帮忙吗?


共1个答案

匿名用户

您必须禁用约束,因为当您尝试输入该行时,父id 1不存在。

CREATE TABLE puffle_item (
  id INT NOT NULL,
  parent_id INT NOT NULL,
  name VARCHAR(50) NOT NULL DEFAULT '',
  type VARCHAR(10) NOT NULL DEFAULT 'care',
  play_external VARCHAR (10) NOT NULL DEFAULT 'none',
  cost INT NOT NULL DEFAULT 0,
  quantity SMALLINT NOT NULL DEFAULT 1,
  member BOOLEAN NOT NULL DEFAULT FALSE,
  food_effect SMALLINT NOT NULL DEFAULT 0,
  rest_effect SMALLINT NOT NULL DEFAULT 0,
  play_effect SMALLINT NOT NULL DEFAULT 0,
  clean_effect SMALLINT NOT NULL DEFAULT 0,
  PRIMARY KEY (id),
  CONSTRAINT puffle_item_ibfk_1 FOREIGN KEY (parent_id) REFERENCES puffle_item (id) ON DELETE CASCADE ON UPDATE CASCADE
);
SET FOREIGN_KEY_CHECKS=0;

INSERT INTO puffle_item (id, parent_id, name, type, play_external, cost, quantity, member, food_effect, rest_effect, play_effect, clean_effect) VALUES (1, 1, 'Brush', 'care', 'none', 0, 1, FALSE, -2, -2, 5, 5);

SET FOREIGN_KEY_CHECKS=1;
select * from puffle_item
id | parent_id | name  | type | play_external | cost | quantity | member | food_effect | rest_effect | play_effect | clean_effect
-: | --------: | :---- | :--- | :------------ | ---: | -------: | -----: | ----------: | ----------: | ----------: | -----------:
 1 |         1 | Brush | care | none          |    0 |        1 |      0 |          -2 |          -2 |           5 |            5

db<;>此处小提琴