简体   繁体   English

MySQL - 也使用外键作为主键

[英]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: 现在有些情况下这种做法可能是一个好主意:

  • if you have lots of users but only a few rows in table 2, perhaps the query on table 2 will be only performed rarely; 如果你有很多用户但只有表2中的几行,那么表2中的查询可能只会很少执行; at the same time, you gain storage space and modification speed on table 1 同时,您获得了表1中的存储空间和修改速度
  • it might be possible in the future for the primary key of table 2 to change, while the foreign key remains; 将来可能有可能改变表2的主键,而外键仍然存在; if you put all the data in table 1, this modification would most likely break your database model 如果将所有数据放在表1中,则此修改很可能会破坏您的数据库模型

It can be a good idea, but it depends on the particulars of your application. 这可能是一个好主意,但这取决于您的应用程序的细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM