Do multiple foreign keys make sense?

can it make sense for a single table multiple foreign keys?

Suppose that I have three tables: Table A, Table Band Table C. If I think of tables as objects (and they are mapped to objects in my code), then both tables A and B have a lot to do with table CIe. Table / object A and B can have many instances of C. So I designed it so that it Table Cpoints to the primary key both in Table Aand Table B: in other words, it Table Chas 2 external (a_Id and b_Id).

Change . I forgot to mention also that it Table Acan have many instances Table B. So it Table Bhas a foreign key in table A. If that matters ...

I wonder if this makes sense or is there a better way to do this? Thank.

+3
source share
5 answers

This is good, but note that this only makes sense if C should always have both A and B as a pair.

If you just want A to have C and B to have C, but A and B are otherwise not connected to each other, you must put the foreign key in and in B and let it be null.

Update: after clarification, it seems that you need two separate relationships: A can have many Cs, and B can have many Cs, but C can belong to only one A or one B.

. " ", A_C B_C . A_C A C. B_C.

+6

, , . , 3-4 . , .

( ) , , .

. PHP MySQL.

+3

A, B, C , FK, .

+3

, . , .

+2

, , , , , . , , , , . , , .

This is not a great solution, but better than adding a new column to the table each time a new role appears, and rewriting the code that runs these queries each time. And I'm sure I can't think of a better way to handle this!

+1
source

Source: https://habr.com/ru/post/1732249/


All Articles