是否有外键作为主键? [英] Is it fine to have foreign key as primary key?

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

问题描述

我有表用户(用户名,密码)和表配置文件(profileId,性别,日期生日,...)。目前我使用这种方法:每个Profile记录有一个名为userId的字段作为外键链接到User表。当用户注册时,将自动创建其个人资料记录。我困惑与我的朋友的建议:有userId字段作为外键和主键,删除profileId字段。哪种方法更好?

解决方案

外键几乎总是允许重复,这将使它们不适合作为主键。 / p>

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



唯一的例外是具有一对一关系的表,其中链接表的外键和主键是一样的。 / p>

I have table "User" (username, password) and table "Profile" (profileId, gender, dateofbirth,...). Currently I'm using this approach: each Profile record has a field named "userId" as foreign key which links to the User table. When an user registers, his Profile record is automatically created. 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.

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天全站免登陆