开发者

To use auto-increment in MySQL or not?

开发者 https://www.devze.com 2023-04-07 18:14 出处:网络
I have read certain places that it is a good practice to typically use an auto-incrementing Primary key for most MySQL tables, rather开发者_C百科 than simply relying on a non-increment field that will

I have read certain places that it is a good practice to typically use an auto-incrementing Primary key for most MySQL tables, rather开发者_C百科 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?


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.


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.


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消