[英]mysql ( innodb )foreign key constraints problems
我在尝试为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中的条目。
当我尝试创建表CI时遇到错误: 错误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
};
奥利·桑德斯(Ollie Saunders)是正确的。 在删除/创建InnoDB表之前,请先删除所有约束。
ALTER TABLE tbl_name
ADD [CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
来源: Alter table语法
每当我这样做时,我肯定会发现最好先定义所有表,然后再对单独的ALTER查询应用约束。 您避免了很多“我需要首先存在此表”这样的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.