I am trying to figure out if it is possible to create a foreign key in this way.
First there are two parent tables in this scenario.
Table 1 has a PK int and another int column. When combined the two are unique.
Table 2 has a PK int and another int column. When combined the two are unique.
The paired value between the two ints is how we currently select the child records for either table.
Table 3 has a value for the PK and other int column from one of the first two tables. It is reliably selectable because the two fields when both used in a search are unique to one of the above tables.
So I am looking to create a FK or possibly two FK for this scenario. I would like to be able to do cascading deletes from either of the first tables into the third table, and would also like to use this for the entity relationships in Entity Framework.
Please let me know if this is not making sense. I have read it several times, and it is about as clear as I can get it.
Thanks
If Table3 contains all values in Table1 UNION Table2, then you have an inheritance scheme:
With that, deleting from Table3 will cascade to Table1 or Table2 appropriately.
Otherwise, if Table3 is just a subset of Table1 UNION Table2 – then introducing Table4 as the full set would work.
To handle cascaded deletes, though, you’d need to delete from Table4 (though you could do a trigger on Table3 to handle that for you).
Edit (because I think it’s an important point that should be seen, seperate from the comments):
IMO – your data model is broken then. Table1 and Table2 are unrelated, but you’re trying to stuff them into the same column in Table3. If Table1 and Table2 are related somehow, then you need to model that.
Either introduce a parent table (Table4) if they’re related, or either a 2nd column in Table3 (Table1 FK, Table2 FK) or 2 join tables if they’re not. Don’t try to put a round peg into a square hole – and don’t try to make up for it with a trigger. 😉