提问人:klyonsie 提问时间:11/16/2023 更新时间:11/16/2023 访问量:21
包含 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
问:
导入数据时,我有
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;
客户可以从不同的商店购买多种产品,因此创建了“order_payment”,用于存储带有产品价格总和的付款。表“order”和“order_payment”工作正常,所以我怀疑“shopping_cart”表的主键有问题。
答:
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);
评论
CREATE
LOAD