见下:create table role(
role_name varchar(20) primary key,
role_id smallint
);create table role_function_mapping(
role_id smallint not null,
function_id smallint not null,
PRIMARY KEY (role_id, function_id),
FOREIGN KEY (role_id) REFERENCES role (role_id) on update cascade,cascade
);如果执行上述SQL语句,那是不行的,因为role_id在表role中不是PK,所以不能在表中role_function_mapping中建立如此外键.
但是,如果我先不管外键,先把表格建立好,再用可视化工具(如企业管理器)把表role_function_mapping中的role_id的修改为外键,那就可以了.请问,这是什么原因?
role_name varchar(20) primary key,
role_id smallint
);create table role_function_mapping(
role_id smallint not null,
function_id smallint not null,
PRIMARY KEY (role_id, function_id),
FOREIGN KEY (role_id) REFERENCES role (role_id) on update cascade,cascade
);如果执行上述SQL语句,那是不行的,因为role_id在表role中不是PK,所以不能在表中role_function_mapping中建立如此外键.
但是,如果我先不管外键,先把表格建立好,再用可视化工具(如企业管理器)把表role_function_mapping中的role_id的修改为外键,那就可以了.请问,这是什么原因?
role_id smallint primary key,
role_name varchar(20)
)
goCreate table role_function_mapping(
role_id smallint not null,
function_id smallint not null
PRIMARY KEY (role_id, function_id)
FOREIGN KEY (role_id) REFERENCES role (role_id) on update cascade
)
我意思是 当role_id不为PK时 为什么sql语句不能写,而可以直接通过工具改
create table role(
role_name varchar(20) primary key,
role_id smallint
)
go
create table role_function_mapping(
role_id smallint not null,
function_id smallint not null,
PRIMARY KEY (role_id, function_id)
)--再用企业管理器在不动任何地方情况下直接来建立role_id的外键,
--你不可能建立成功的嘛
说说我的看法 如果有不对请指出
lz的create table role_function_mapping里的
FOREIGN KEY...REFERENCES
是为列中数据提供引用完整性的约束。FOREIGN KEY 约束要求列中的每个值在被引用表的指定列中都存在--引用联机帮助, 这也是lz提到的为什么不能创建外键而lz说的
但是,如果我先不管外键,先把表格建立好,再用可视化工具(如企业管理器)把表role_function_mapping中的role_id的修改为外键,那就可以了
-----------------------------------------------------------------------------
在企业管理器里建立的是关系图 并不是pk约束,一个表只能有一个pk约束这是肯定的,所有把function _id 的pk去掉后 肯定是可以建立的fk的。但是和建立约束是不一样的。