When to use one field as primary key instead of 2?

后端 未结 4 1067
借酒劲吻你
借酒劲吻你 2020-12-12 03:11

I often see some database design like this:

Case 1:

UserTable

--id[auto increase]

--UserName

--Password

--Em

4条回答
  •  离开以前
    2020-12-12 03:30

    Several reason I can think of in your example for using a surrogate primary key (Id) over the username.

    1. The id field would be very rarely subject to updates if at all. If username was the primary key you would have to cascade on update to all tables where username was used as a foreign key.
    2. Performance. An int comparison beats a string comparison.
    3. The id key would take up less storage space where it was a foreign key in other tables.
    4. the id field allows you to not expose perhaps sensitive data. E.g. consider a web app url domain/posts/user/1242 vs domain/posts/user/myusername

    For your second question it would be better to use userid than the username in UserTableRole. Whether or not it is better to then also include a surrogate key for this many- to- many table is a matter of opinion. I hate using surrogate id keys for many to many tables and usually just make a compound primary key of the two foreign key ids. The only time I would consider a surrogate key here is if I needed to use it as a foreign key in yet another table.

提交回复
热议问题