4

我试图将数据插入表中Bookratings,但我不断收到此错误消息。这是因为当我尝试插入时,它会在Bookratings表中创建重复项,这是 PRIMARY 键约束不允许的吗?

MySQL 错误 1452 - 无法添加或更新子行:外键约束失败

在此处输入图像描述

我的实际代码:

如果存在 amazon2,则删除数据库;

如果不存在 amazon2,则创建数据库;

使用亚马逊2;

create table books(  
  ISBN varchar(13),
  Title varchar(255),
  Author varchar(255),
  Year int(10),
  Puplisher varchar(255),
  ImageURL varchar(255),
  Genre varchar(12),
  unitprice decimal(6,2),
  primary key (ISBN)
); 


  create table users(
    UserID int(11),
    Country varchar(250),
    Age int(11),
    primary key (UserID)
  );


  create table bookratings(
    UserID int(11) not null,
    ISBN varchar(13) not null,
    Rating int(11),
    primary key (UserID, ISBN),
    foreign key (ISBN) references books (ISBN) on delete cascade on update cascade,
    foreign key (UserID) references users (UserID) on delete cascade on update cascade
   );


   create table orders(
     OrderID int(11),
     UserID int(11) not null,
     Year int(10),
     totalpay decimal(6,2),
     primary key (OrderID),
     foreign key (UserID) references users (UserID)
   );


   create table trans(
     OrderID int(11) not null,
     ISBN varchar(13) not null,
     Quantity int(11),
     primary key (OrderID, ISBN),
     foreign key (OrderID) references orders (OrderID),
     foreign key (ISBN) references books (ISBN)
   );

我必须澄清一些事情:根据任务,我不允许添加任何其他属性或删除现有属性。

4

1 回答 1

9

违反外键约束意味着您尝试更新的表包含对其他表的引用,并且您以某种方式破坏了该引用。

如果我有一张桌子电影

+----------+---------------+
| Movie_ID |  Movie_Name   |
+----------+---------------+
|        1 | Jaws          |
|        2 | Star-Wars     |
|        3 | Jurassic Park |
+----------+---------------+

和一个表 User_Reviews

+---------+----------+-------+
| User_ID | Movie_ID | Score |
+---------+----------+-------+
|       1 |        1 | 2.5   |
|       2 |        1 | 5     |
|       3 |        2 | 4     |
|       4 |        2 | 3     |
|       5 |        2 | 4.5   |
|       6 |        3 | 5     |
+---------+----------+-------+

在 User_Reviews 表中,Movie_ID 是一个外键。

我无法对 Movie_ID = 10 进行评论,因为电影表中不存在该电影。如果我确实尝试这样做,我会得到一个外键约束错误。

于 2017-12-05T19:49:23.307 回答