关于两个表之间字段关联的问题

来源:百度知道 编辑:UC知道 时间:2024/06/03 04:02:01
请教大家一个问题 现在我一个库中有两个表,表1是记录产品类别的名称
表2是具体的产品
我想做到当我修改表1的bigclassname字段时 表2的classname就跟着主动的更新
例如我把表1的bigclassname的水果更新为水果类 那么表2的classname就跟着主动的更新为水果类
这个要怎么做啊
表1:bigclassname
id bigclassname
1 文具
2 水果
3 蔬菜

表2:Record
id products classname
1 香蕉 水果
2 苹果 水果
3 橘子 水果
4 白菜 蔬菜
5 韭菜 蔬菜
6 铅笔 文具

用级联更新,楼主的record应该引用表1的ID,不应该用Name

alter table record add constraint FK_record foreign key(ClassID)references bigclassname(ID) on update cascade

go
没有关系记录className时,用触发器
--每次只可更新一个bigclassname
create trigger tr_bigclassname on bigclassname
after update
as

update record
set ClassName =(select top 1 bigclassname from inserted)
where ClassName in(select bigclassname from deleted)

没有关联更新的功能,只有自己的程序在每次更新表1的时候记住同时更新表2。

不过我建议你在表2里面,不存储classname(水果、蔬菜),而只保存classid(1、3),这样只有不修改表1的id,无论怎么修改类别都是对的。而且当类别名字占用的存储比id大得多的时候,你这样的方式其实因为表2里面存储类别名称而浪费了许多空间。

这个已经不是字段关联问题,
这个是需要数据库同步

你看看数据表设计的几个范式。
表二里你不应存类别的汉字而是存表一里类别对应的id