MySQL - 也使用外键作为主键 [英] MySQL - Using foreign key as primary key too

查看:163
本文介绍了MySQL - 也使用外键作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主键 user_id 和表2,其中 user_id 是一个外键。 p>

每个 user_id 只有一条记录可以存在于表2中,没有记录就不会存在。



问题:表2中的 user_id 是否同时是外键和主键,如果是的话,是不是一个好主意,什么是优点/缺点?是的,你可以做到这一点(你应该从数据库设计的角度来看, )。

但是,如果 user_id 是表2中的主键,请考虑这意味着什么。说表2中的每一行对应于一个用户,但是你已经有了一个表,其中每一行对应于一个用户:表1.这提出了一个问题:为什么不把表2中的所有数据都放到可空列表格1?。毕竟,有两个表意味着你将不得不做两个查询来获得这个数据,而不是一个。



现在有一些情况下,这种做法可能是一个好主意:


  • 如果表2中只有很少的用户,但只有几行,表2中的查询可能只会执行很少;与此同时,你获得了表1中的存储空间和修改速度

  • 将来可能会改变表2的主键,而外键仍然存在;如果你把所有的数据放在表1中,这个修改很可能会破坏你的数据库模型。$ ​​b

    $ b

    这可能是个好主意,但这取决于你的申请的细节。


    I have table 1 with a primary key user_id and table 2 where user_id is a foreign key.

    Only 1 record per user_id can exist in table 2, and no record can exist without it.

    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?

    解决方案

    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?". 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; at the same time, you gain storage space and modification speed on table 1
    • it might be possible in the future for the primary key of table 2 to change, while the foreign key remains; if you put all the data in table 1, this modification would most likely break your database model

    It can be a good idea, but it depends on the particulars of your application.

    这篇关于MySQL - 也使用外键作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆