如何能在2个表的字段之间建立类似外键的约束关系
比如有2个表
readertype:
typeid(primary key)
typename
booknumber.....
reader:
readerid(primary key)
readername
readertype.....
由于typename不是主键,所以就不能readertype设为外键,将而我要想在typename和readertype建立类似外键的约束关系,请问如何解决
[解决办法]
例子一个:
create table a1(produce varchar(10) primary key)
insert into a1 select 'A '
insert into a1 select 'B '
insert into a1 select 'C '
insert into a1 select 'D '
insert into a1 select 'E '
create table a2(produce varchar(10) not null
foreign key references a1(produce) on delete cascade
on update cascade--建表时就这样定义(更新与删除)
,val int)
insert into a2 select 'A ',1
insert into a2 select 'B ',2
insert into a2 select 'C ',3
insert into a2 select 'D ',4
insert into a2 select 'E ',5
测试更新:
update a1
set produce= 'A1 '
where produce= 'A '
select * from a2
alter table a2 add constraint a2_con foreign key(produce)references a1(produce) on delete cascade on update cascade
delete from a1 where produce= 'a '
select * from a1
select * from a2
drop table a1,a2
[解决办法]
用触发器
[解决办法]
用触发器吧,不过感觉你的两个表是不是有数据冗余呢?是不是可以drop掉readername,
readertype,在查询的时候直接join readertype表来获得呢?