简体   繁体   English

要在MySQL中使用自动增量吗?

[英]To use auto-increment in MySQL or not?

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. 我已经读过某些地方,通常对大多数MySQL表使用自动递增主键,而不是仅仅依赖于将强制实施为唯一的非递增字段,这是一个好习惯。

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? Authors表是否也应具有自己的自动递增主键,还是应该依赖user_id外键作为主键?

ALSO

Are there noticeable performance reasons to NOT use the auto-incrementing id as the Primary? 是否有明显的性能原因不将自动增量ID用作主要ID?

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. user表和author表都应具有单独的主键。 (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. PS-我的命名首选项对于表格是单数。 It should be user and author tables. 它应该是userauthor表。 They happen to contain multiple rows, but a single row means a single entity. 它们碰巧包含多行,但单行表示单个实体。

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

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. 如果每个作者都恰好映射到一个用户(并且您确定这不会改变),则可以不用将user_id作为主键。 If not, you'll need an independent primary key for Authors . 如果不是,则需要Authors的独立主键。

(Note that the reverse relation doesn't have to be true: not every user has to map to an author.) (请注意,反向关系不必为真:并非每个用户都必须映射到作者。)

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

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