包含 2 个外键作为主键和其他外键的表“shopping_cart”在导入数据时出现关系错误

Table 'shopping_cart', which contains 2 foreign key as primary key and other foreign key, have an error with relationship while importing data

提问人:klyonsie 提问时间:11/16/2023 更新时间:11/16/2023 访问量:21

问:

导入数据时,我有

Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`mydb_innodb`.`shopping_cart`, CONSTRAINT `fk_shopping_cart_order_payment1` FOREIGN KEY (`paypal_transaction_id`) REFERENCES `order_payment` (`paypal_transaction_id`))

用于创建“shopping_cart”和“order_payment”表的MySQL脚本:

CREATE TABLE IF NOT EXISTS `mydb_innodb`.`order_payment` (
  `paypal_transaction_id` VARCHAR(45) NOT NULL,
  `paid_by` VARCHAR(91) NOT NULL,
  `is_paypal_verified` TINYINT NOT NULL,
  `is_shipping_address_confirmed` TINYINT NOT NULL,
  `total_price` FLOAT NOT NULL,
  PRIMARY KEY (`paypal_transaction_id`))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `mydb_innodb`.`shopping_cart` (
  `product_id` INT NOT NULL,
  `shop_id` INT NOT NULL,
  `paypal_transaction_id` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`product_id`, `shop_id`),
  INDEX `fk_shopping_cart_product1_idx` (`product_id` ASC, `shop_id` ASC) VISIBLE,
  INDEX `fk_shopping_cart_order_payment1_idx` (`paypal_transaction_id` ASC) VISIBLE,
  CONSTRAINT `fk_shopping_cart_product1`
    FOREIGN KEY (`product_id` , `shop_id`)
    REFERENCES `mydb_innodb`.`product` (`id` , `shop_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_shopping_cart_order_payment1`
    FOREIGN KEY (`paypal_transaction_id`)
    REFERENCES `mydb_innodb`.`order_payment` (`paypal_transaction_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

EER图

客户可以从不同的商店购买多种产品,因此创建了“order_payment”,用于存储带有产品价格总和的付款。表“order”和“order_payment”工作正常,所以我怀疑“shopping_cart”表的主键有问题。

MySQL 数据库设计 数据库关系

评论

1赞 P.Salmon 11/16/2023
'所以我怀疑,'shopping_cart'表的主键有问题。“ - 不,错误很明显,您需要在子项(shopping_cart)之前创建父级(即order_payment)。
0赞 klyonsie 11/16/2023
谢谢,我首先创建了父母。问题出在导入数据时,使用“LOAD DATA INFILE”,我有“LINES TERMINATED BY \n”而不是“LINES TERMINATED BY \r\n”。
0赞 philipxy 11/17/2023
调试问题需要一个最小的可重现示例。PS 为什么我不应该上传代码/数据/错误的图片?ERD 是 DDL 的映像。但是:在你的帖子中放上需要的东西,但只写需要问的东西。
0赞 Rick James 11/19/2023
错误是来自还是来自?CREATELOAD

答:

0赞 klyonsie 11/16/2023 #1

问题在于使用 导入数据时,我有 ,而不是 。MySQL在导入数据时会找到回车符()和换行符()。'LOAD DATA INFILE'LINES TERMINATED BY '\n'LINES TERMINATED BY '\r\n'\r\n

完整代码:

LOAD DATA INFILE 'fake_shopping_carts.csv' INTO TABLE shopping_cart
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 ROWS
(product_id, shop_id, paypal_transaction_id);