3

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

错误是 1005: Can't create table blocks.frm (errno 150) on a mysql 5.0

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;

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

4

2 回答 2

5

将 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);
于 2009-02-15T18:20:56.643 回答
0

您可以延迟外键检查,直到创建表:

SET FOREIGN_KEY_CHECKS = 0;
CREATE TABLE ...;
SET FOREIGN_KEY_CHECKS = 1;
于 2009-02-15T20:42:29.347 回答