MySQL 是否使用自增?

发布于 2024-12-06 14:07:31 字数 352 浏览 1 评论 0原文

我在某些地方读到,对于大多数 MySQL 表来说,通常使用自动增量主键是一个很好的做法,而不是简单地依赖于强制唯一的非增量字段。

我的问题具体是关于用户表以及通过外键连接到它的表。架构如下:

TABLE Users {
    id
    name
    ...
}

TABLE Authors {
    user_id (FK)
    author_bio
}

Authors 表是否也应该有自己的自动递增主键,还是应该依赖 user_id 外键作为主键?

另外

是否有明显的性能原因导致不使用自动递增 id 作为主 ID?

I have read certain places that it is a good practice to typically use an auto-incrementing Primary key for most MySQL tables, rather than simply relying on a non-increment field that will be enforced to be unique.

My question is specifically about a User table, and a table connected to it by a Foreign Key. Here's the schema:

TABLE Users {
    id
    name
    ...
}

TABLE Authors {
    user_id (FK)
    author_bio
}

Should the Authors table have its own auto-incrementing primary key as well, or should it rely on the user_id foreign key as a primary key?

ALSO

Are there noticeable performance reasons to NOT use the auto-incrementing id as the Primary?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

天生の放荡 2024-12-13 14:07:31

这不是非此即彼的问题。如果您使用自动增量主键,并且您有需要强制实施约束的候选键,那么您的架构应该同时拥有这两个主键。

您的 userauthor 表都应该有单独的主键。 (每个表必须有一个主键。)我不会使用外键作为主键。如果确实如此,我就不会有单独的作者表;我将这些列放入用户表中。

PS - 我对表的命名偏好是单一的。它应该是 userauthor 表。它们恰好包含多行,但单行意味着单个实体。

It's not either-or. If you use an auto increment primary key, and you have candidate keys that need to enforce constraints, then your schema should have both.

Both your user and author tables should have individual primary keys. (Every table must have a primary key.) I would not use the foreign key as the primary key. If that truly is the case, I wouldn't have a separate author table; I'd put those columns in the user table.

PS - My naming preference is singular for tables. It should be user and author tables. They happen to contain multiple rows, but a single row means a single entity.

凉薄对峙 2024-12-13 14:07:31

您肯定希望 Authors 表拥有自己的主键,例如 authors_id,然后将 user_id 作为外键。

You most definitely want the Authors table to have its own primary key such as authors_id, and then have user_id as a foreign key.

深居我梦 2024-12-13 14:07:31

这取决于您想要实现的目标。如果每个作者都映射到一个用户(并且您确定这不会改变),则可以将 user_id 作为主键。如果没有,您将需要 Authors 的独立主键。

(请注意,反向关系不必为真:并非每个用户都必须映射到作者。)

It depends on what you're trying to accomplish. If every author maps to exactly one user (and you're sure this isn't going to change), you can get away with having user_id as a primary key. If not, you'll need an independent primary key for Authors.

(Note that the reverse relation doesn't have to be true: not every user has to map to an author.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文