Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 965
Duncan Gravill Avatar asked Jun 12 '11 18:06

Duncan Gravill


2 Answers

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

  • Scalar UDFs wrapped in CHECK constraints are very slow and may fail for multirow updates
  • Tony Rogerson

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.
like image 130
gbn Avatar answered Oct 23 '22 10:10

gbn


Yes, this is possible using CHECK constraints.

Apart from the normal foreign key constraint, you will need to add a CHECK constraint on both referencing tables to ensure that a foreign key is not used in the other referencing table.

like image 38
Oded Avatar answered Oct 23 '22 11:10

Oded