Proper way to use foreign keys

Hi,

What is the best way of using foreign keys if I want to bind informations that are stored in two different tables? (The relation is one-to-one so the arrows would have the same arrowhead from start to finish).

I post the two methods I use here, please, I would to know, what is the proper one? Thanks!
(I usually use MySQL and PHP.)

the first way allows many-to-many relationships, but is still quite valid even if populated with only one-to-one data

for the second way, i would suggest that you try creating that schema with actual CREATE and ALTER statements, to learn how difficult that is… and then try loading some data into those tables

method “2A” would be to have just one FK instead of two – which one do you think is the more important one? are both FK relationships really one-to-one, or is one of them “one-to-zero-or-one”?

also, there’s a third way – a single table

ok, thanks!

ok![quote=“r937, post:2, topic:238977”]
for the second way, i would suggest that you try creating that schema with actual CREATE and ALTER statements, to learn how difficult that is… and then try loading some data into those tables
[/quote]

hmm…, I think that I can’t INSERT in all the fields with a single query. A way to proceed may be to INSERT in the first table and retrieve the last id, then INSERT in the second table and retrieve the last id and then UPDATE the FK in both tables with the respective retrieved id values! if I’m right… yes, difficult! :

so, I think this would be good:

yes, the simplest, and I think the clearerest way :slight_smile:

1 Like

You will need foreign keys if you are splitting your database into tables and you are working with a DBMS (e.g. MySQL, Oracle and others)

actually, it is quite possible to work with a DBMS without using foreign keys at all

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.