MySQL 在数据库设计中使用用户名作为主键是不是很糟糕?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1825613/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it bad to use user name as primary key in database design?
提问by Steven
I was told by a friend:
有朋友告诉我:
What unique key do you use? I hope you are not saving the entire user name --- this will use up too much table space! Assign an unique userID to each (unique) userNAME and save this userID (should be INTEGER UNSIGNED auto_increment or BIGINT UNSIGNED auto_increment). Don't forget to create a reference
FOREIGN KEY (
userID
) REFERENCESusertable
(userID
) in all tables using the userID.
您使用什么唯一键?我希望您不要保存整个用户名 --- 这会占用太多表空间!为每个(唯一的)userNAME 分配一个唯一的 userID 并保存这个 userID(应该是 INTEGER UNSIGNED auto_increment 或 BIGINT UNSIGNED auto_increment)。不要忘记创建参考
FOREIGN KEY (
userID
) REFERENCESusertable
(userID
) 在所有使用 userID 的表中。
Is the above statement correct? Why or why not?
以上说法正确吗?为什么或者为什么不?
回答by Graviton
I think he is right ( for the wrong reason) because primary key cannot change, but username
can change. So you should use userid
because it wouldn't change.
我认为他是对的(出于错误的原因),因为主键不能改变,但username
可以改变。所以你应该使用,userid
因为它不会改变。
回答by Vinko Vrsalovic
He is right for the wrong reasons. The table space is secondary to the fact that your app might later mandate that usernames can be changed or even stop being unique (you could envision an application where unique usernames are not required, like Stack Overflow) and thus your app would need major refactoring and data migration instead of a light change in the other (integer PK) case.
出于错误的原因,他是对的。表空间是次要的,因为您的应用程序稍后可能会要求用户名可以更改甚至不再是唯一的(您可以设想一个不需要唯一用户名的应用程序,例如 Stack Overflow),因此您的应用程序需要进行重大重构和数据迁移而不是其他(整数 PK)情况下的轻微变化。