问题
Say,
I have 3 tables.
User
which contains basic info about the users.
SectionA
which contains more info about the user.
SectionB
which also contains more info about the user.
There can only be one SectionA
and SectionB
data for each user.
My idea was to create a table design like this:
id name section_a_id section_b_id
1 matt 1 1
Problem is, section_a_id
and section_b_id
cannot be auto incremented since they are not primary keys.
So I tried a different approach and decided that the id
primary key in User
should be a foreign key that refers to section_a_id
and section_b_id`. But I'm unable to do so since mysql will only allow a reference to one table.
So how should I approach this situation?
回答1:
If it's one to one relation, it will always be easier to combine the three tables into one big table, with nullable columns for Section tables.
Some positive points I can see for this approach:
- Easier insert, update and delete operations.
- Faster data retrieval when there are less joins to use.
- Less indexes space, because you are indexing the primary key for one table instead of three tables.
回答2:
It seems you have:
- 1-n User-SectionA relation
- 1-n User-SectionB relation
so the foreign keys have to be in SectionA and SectionB tables and they have to be the User table primary key.
回答3:
There can only be one SectionA and SectionB data for each user.
This begs the question of why you are storing the data in different tables. That is sometimes a fine thing to do -- different users might be in different tables.
One solution is to have the primary key of SectionA
and SectionB
be a foreign reference to the UserId
. Yes, this is allowed.
Another solution is to have the sectionA_id
and sectionB_id
in the users
table. Then you can have an auto-incremented id in each of the referenced tables.
回答4:
Rare uses for 1:1
- You really have too many columns;
- The table is huge and you don't want to ALTER the table to add more;
- One of the tables is mostly optional, and you use
LEFT JOIN
to get nulls.
Righting some AUTO_INCREMENT
misconceptions
- The column does not have to be the
PRIMARY KEY
, nor evenUNIQUE
; it only needs to be the first column in some index. - You do not have to have an
AUTO_INCREMENT
column at all. It is often better to use a "natural" PK -- some column (or combination of columns) that is inherentlyUNIQUE
.
When building a pair of 1:1 tables, this is one way to do it
- Build the first table with a
PRIMARY KEY
that isAUTO_INCREMENT
. - Build the second table with a
PRIMARY KEY
that is identical to the other, but notAUTO_INCREMENT
. - When inserting a row, use
LAST_INSERT_ID()
to get the id. - Use that value for explicitly specifying the id for the second table.
来源:https://stackoverflow.com/questions/45914666/one-to-one-relationship-involving-multiple-tables