尝试为MySql(Innodb)中的表生成外键时遇到了两个问题。你能帮我吗?
参考表:
*create table entity
{
PID INT(20) auto inc not null,
ENTITYID INT(20) not null,
details VARCHAR(100) not null,
primary key(PID,ENTITYID)
}
create table user
{
USERID int(20) auto inc not null,
NAME VARCHAR(45) not null,
joindate DATETIME not null,
location VARCHAR(100) not null,
primary key(USERID,NAME) not null
}*
Referencing table:
*create table C
{
ENTITYID INT(20) not null,
NAME VARCHAR(45) not null,
foreign key ENTITYID_C constraint ENTITYID references entity(ENTITYID) on delete cascade,
foreign key name_C constraint NAME references user(NAME) on delete cascade,
primary key(ENTITYID,NAME)
}*
我需要在表C中使用2个外键,因为在删除相应实体或相应用户时,必须删除C中的条目。
当我尝试创建表C时遇到错误:错误1005:无法创建表(错误号:150)。我怀疑这是因为我不遵守mysql规范中规定的规则。
http://dev.mysql.com/doc/refman/5.4/en/innodb-foreign-key-constraints.html
规格的以下部分/规则是什么意思?
“ InnoDB要求在外键和引用键上建立索引,以便外键检查可以快速进行,而无需进行表扫描。在引用表中,必须有一个索引,其中外键列以相同的顺序列为第一列。”
这是否意味着表C中的外键需要与实体表和用户表中的主键相对应,以便实体表中的ENTITYID必须在主键中是第一个,而用户表中的NAME必须在主键中是第一个。
换句话说,我的主键声明应按以下方式重写吗?
entity table --> primary key(ENTITYID,PID) ,
user table --> primary key(NAME,USERID)
如果是这样,当我尝试如上所述对键声明进行重新排序时,我会遇到错误1075。
“表定义不正确,只能有一个自动列,必须将其定义为键。”
如何使自动递增键(代理键)在索引顺序列表中排第二,以便我符合规范?
谢谢 !
最佳答案
我认为您的实体和用户主键不正确。我相信您的主键和索引混杂在一起。
两个表都有自动递增列。我认为这些应该是主键-ENTITY为PID,USER为USERID。如果您使用ENTITYID来查询ENTITY,或者使用NAME来查询USER,则一定要为两者创建索引。
现在,表C定义了ENTITY和USER之间的多对多关系。 C中有两列指向PID和USERID,每列都有外键。 C的主键只是两者的组合。
像这样:
create table entity
{
pid int(20) auto inc not null,
primary key(pid)
};
create table user
{
userid int(20) auto inc not null,
primary key(userid)
};
create table user_entity
{
entity_id int(20) not null,
user_id int(20) not null,
primary key(entity_id, user_id)
foreign key entity_id references entity(pid) on delete cascade,
foreign key user_id references user(userid) on delete cascade
};
关于mysql - mysql(innodb)外键约束问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1575905/