Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server foreign key to multiple tables

I have the following database schema:

members_company1(id, name, ...);
members_company2(id, name, ...);
profiles(memberid, membertypeid, ...);
membertypes(id, name, ...)
[ 
       { id : 1, name : 'company1', ... }, 
       { id : 2, name : 'company2', ... }
];

So each profile belongs to a certain member either from company1 or company2 depending on membertypeid value

members_company1     —————————      members_company2     
————————————————                    ————————————————
id      ——————————> memberid <———————————         id
name               membertypeid                 name
                       /|\
                        |  
                        |  
      profiles          |  
      ——————————        |  
      memberid  ————————+  
      membertypeid

I am wondering if it's possible to create a foreign key in profiles table for referential integrity based on memberid and membertypeid pair to reference either members_company1 or members_company2 table records?

like image 637
Maksim Vi. Avatar asked Apr 10 '13 20:04

Maksim Vi.


People also ask

Can a foreign key connect to multiple tables?

A table can have multiple foreign keys based on the requirement.

Can a foreign key reference multiple tables in SQL?

A foreign key is a key used to link two tables together. This is sometimes also called as a referencing key. A Foreign Key is a column or a combination of columns whose values match a Primary Key in a different table.

Why do we prefer setting a foreign key when we work on two tables?

A primary key ensures unique row identification. This results in faster sorting, searching, and querying operations. A foreign key creates a link between two tables. It maintains referential integrity between the referencing column(s) and the referenced column(s).

Can a foreign key reference multiple columns of the parent table?

No. A foreign key constraint names exactly which table and column(s) it references, and it must reference the same table and column(s) on every row.


1 Answers

A foreign key can only reference one table, as stated in the documentation (emphasis mine):

A foreign key (FK) is a column or combination of columns that is used to establish and enforce a link between the data in two tables.

But if you want to start cleaning things up you could create a members table as @KevinCrowell suggested, populate it from the two members_company tables and replace them with views. You can use INSTEAD OF triggers on the views to 'redirect' updates to the new table. This is still some work, but it would be one way to fix your data model without breaking existing applications (if it's feasible in your situation, of course)

like image 85
Pondlife Avatar answered Nov 10 '22 06:11

Pondlife