[英]MySQL - Using foreign key as primary key too
I have table 1 with a primary key user_id
and table 2 where user_id
is a foreign key. 我有一个主键为
user_id
表1和表2,其中user_id
是一个外键。
Only 1 record per user_id
can exist in table 2, and no record can exist without it. 表2中每个
user_id
只能存在1条记录,没有它就不能存在记录。
QUESTION: Can user_id
in table 2 be both foreign and primary key at the same time, and if yes, is it a good idea, what are pros/cons? 问题:表2中的
user_id
可以同时是外键和主键,如果是,那么它是一个好主意,有什么利弊?
Yes, you can do this (and you should, from a database design point of view). 是的,您可以这样做(从数据库设计的角度来看,您应该这样做)。
However, consider what it means if user_id
is the primary key on table 2. You are in effect saying that each row in table 2 corresponds to a user, but you already have a table where each row corresponds to a user: table 1. This raises the question "why then don't you put all data of table 2 into nullable columns in table 1?". 但是,请考虑如果
user_id
是表2上的主键,这意味着什么。您实际上是说表2中的每一行对应一个用户,但您已经有一个表,其中每行对应一个用户:表1.这提出了一个问题“为什么不把表2中的所有数据都放入表1中的可空列?”。 After all, having two tables means you will have to make two queries to get this data instead of one. 毕竟,拥有两个表意味着您将不得不进行两次查询来获取此数据而不是一个。
Now there are some scenarios where this practice might be a good idea: 现在有些情况下这种做法可能是一个好主意:
It can be a good idea, but it depends on the particulars of your application. 这可能是一个好主意,但这取决于您的应用程序的细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.