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

问题描述 投票:0回答:1

导入数据时,我有

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 Diagram

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

mysql database database-design relational-database relationship
1个回答
0
投票

问题是使用

'LOAD DATA INFILE'
导入数据,我有
LINES TERMINATED BY '\n'
而不是
LINES TERMINATED BY '\r\n'
。 MySQL在导入数据时会发现回车(
\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);
© www.soinside.com 2019 - 2024. All rights reserved.