Mad*_*ald 2 mysql foreign-keys mysql-error-1452
我试图将数据插入表中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)
);
Run Code Online (Sandbox Code Playgroud)
我必须澄清一些事情:根据任务,我不允许添加任何其他属性或删除现有属性。
外键约束违规意味着您尝试更新的表包含对其他表的引用,并且您以某种方式破坏了该引用。
如果我有一张桌子电影
+----------+---------------+
| Movie_ID | Movie_Name |
+----------+---------------+
| 1 | Jaws |
| 2 | Star-Wars |
| 3 | Jurassic Park |
+----------+---------------+
Run Code Online (Sandbox Code Playgroud)
还有一个表 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 |
+---------+----------+-------+
Run Code Online (Sandbox Code Playgroud)
在 User_Reviews 表中,Movie_ID 是外键。
我无法使用 Movie_ID = 10 进行评论,因为 Movies 表中不存在该电影。如果我确实尝试这样做,我会收到外键约束错误。
| 归档时间: |
|
| 查看次数: |
3554 次 |
| 最近记录: |