【发布时间】:2009-11-03 16:59:02
【问题描述】:
我有一个数据库应用程序,其中一个组是这样建模的:
TABLE Group
(
group_id integer primary key,
group_owner_id integer
)
TABLE GroupItem
(
item_id integer primary key,
group_id integer,
group_owner_id integer,
Foreign Key (group_id, group_owner_id) references Group(group_id, group_owner_id)
)
我们设置了一个包含group_owner_id 的多字段外键,因为我们要确保GroupItem 的所有者不能与它所在的Group 的所有者不同。出于其他原因(我不认为我需要详细说明)group_owner_id 无法从GroupItem 表中删除,因此仅删除它不是一种选择。
我的大问题是如果我想为整个组更新group_owner_id,我正在编写这样的代码(在伪代码中):
...
BeginTransaction();
BreakForeignKeys(group_items);
SetOwnerId(group, new_owner_id);
SaveGroup(group);
SetOwnerId(group_items, new_owner_id);
SetForeignKeys(group_items, group);
SaveGroupItems(group_items);
CommitTransaction()
...
有没有办法解决这个问题?它似乎有点笨拙。希望我已经发布了足够的详细信息。
谢谢。
【问题讨论】:
标签: sql sql-server foreign-key-relationship