gpt4 book ai didi

sql - SQL中的交叉外键

转载 作者:行者123 更新时间:2023-12-04 23:44:21 25 4
gpt4 key购买 nike

我正在尝试创建 2 个带有交叉外键的表,但在创建它们时不允许我引用不存在的表。任何为 mysql 创建这样的表的方法,比如同时声明两个表或延迟外键的评估?

错误是 1005:无法在 mysql 5.0 上创建表 blocks.frm (errno 150)

SQL:

create table if not exists blocks( 
id int unsigned not null auto_increment,
title varchar(100),
defaultpage int unsigned not null,
foreign key(defaultpage) references pages(pageID),
primary key(id)) engine=innodb;

create table if not exists pages(
pageID int unsigned not null auto_increment,
title varchar(50) not null,
content blob,
blockid int unsigned not null,
foreign key(blockid) references block(id),
primary key(pageID) ) engine=innodb;

解决问题的正确方法是什么?

最佳答案

将 cletus 的答案(完全正确)带入代码...

create table if not exists pages( 
pageID int unsigned not null auto_increment,
title varchar(50) not null,
content blob,
blockid int unsigned not null,
primary key(pageID) ) engine=innodb;

create table if not exists blocks(
id int unsigned not null auto_increment,
title varchar(100),
defaultpage int unsigned not null,
foreign key(defaultpage) references pages(pageID),
primary key(id)) engine=innodb;

alter table pages add constraint fk_pages_blockid foreign key (blockid) references blocks (id);

关于sql - SQL中的交叉外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/551309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com