外键作为主键可以吗? [英] Is it fine to have foreign key as primary key?

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

问题描述

我有两张桌子:

  • 用户(用户名、密码)
  • 个人资料(个人资料 ID、性别、出生日期等)

目前我正在使用这种方法:每个配置文件记录都有一个名为userId"的字段作为外键,它链接到用户表.当用户注册时,他的个人资料记录会自动创建.

Currently I'm using this approach: each Profile record has a field named "userId" as foreign key which links to the User table. When a user registers, his Profile record is automatically created.

我对我朋友的建议感到困惑:将userId"字段作为 foreignprimary 键并删除profileId"字段.哪种方法更好?

I'm confused with my friend suggestion: to have the "userId" field as the foreign and primary key and delete the "profileId" field. Which approach is better?

推荐答案

外键几乎总是允许重复",这会使它们不适合作为主键.

Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.

相反,找到一个唯一标识表中每条记录的字段,或添加一个新字段(自动递增的整数或 GUID)作为主键.

Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.

唯一的例外是带有的表格一对一的关系,其中链接表的外键键是一回事.

The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.

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

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