开发者

optional foreign keys one of which must be mandatory - how?

开发者 https://www.devze.com 2023-04-10 23:09 出处:网络
I have a table that has two optional foreign keys, each to a different table and one of which HAS to be filled in, but it doesn\'t matter which one.I was thinking about using a trigger to enforce this

I have a table that has two optional foreign keys, each to a different table and one of which HAS to be filled in, but it doesn't matter which one. I was thinking about using a trigger to enforce this "constraint", but it feels wrong doing it that way. I am not able to redesign th开发者_Python百科e tables, so I am stuck with it.

We are using Oracle 10g

Is there a better way to do this?

EDIT: I accidentally left out some of the info. At least one column HAS to be filled in, and ONLY one column CAN be filled in.


Use a check constraint. If they can both be populated then:

 alter table t add constraint c check (col1 is not null or col2 is not null)

Or if they are mutually exclusive:

 alter table t add constraint c check ((col1 is not null and col2 is null
                                       or (col2 is not null and col1 is null))


Create another table to be parent of the two tables you are referencing at the moment. Reference that new table with just one foreign key (non-nullable) instead of two. In other words use a supertype / subtype pattern.

0

精彩评论

暂无评论...
验证码 换一张
取 消