MySQL - 无法添加或更新子行

MySQL - Cannot add or update a child row

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

ERROR 1452 (23000) at line 8613: Cannot add or update a child row: a foreign key constraint fails

第 8613 行:INSERT INTO puffle_item (id, parent_id, name, type, play_external, cost, quantity, member, food_effect, rest_effect, play_effect, clean_effect) VALUES

Table指的是:

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
);

试图放入 table 的项目示例: (1, 1, 'Brush', 'care', 'none', 0, 1, FALSE, -2, -2, 5, 5),

有什么帮助吗?

您必须禁用约束,因为在您尝试输入该行时父 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<>fiddle here