Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

sql - A constraint that only allows one of two tables to reference a base table

I have 3 tables. A base table, call it Table A, and two tables that reference Table A, Call them Table X and Table Y. Both X and Y have a foreign key contraint that references Table A. The Foreign Key of X and Y is also their own Primary Key.

I'd like to know if it is possible to add a constraint that will only allow one of these tables to contain a recrod that references Table A. So if X has a record that references A then Y can't have one and if Y has a record that references A then X can't have one.

Is this possible?

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CHECK constraints with UDFs (which is Oded's answer) don't scale well and have poor concurrency. See these:

So:

  • create a new table, say TableA2XY
  • this has the PK of TableA and a char(1) column with a CHECK to allow ony X or Y. And a unique constraint on the PK of A too.
  • tableX and tableY have new char(1) column with a check to allow only X or Y respectively
  • tableX and tableY have their FK to TableA2XY on both columns

This is the superkey or subtype approach

  • all DRI based
  • no triggers
  • no udfs with table access in CHECK constraints.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...