与自动递增的数字相比,电子邮件地址是一个糟糕的初选候选人吗?
我们的web应用程序需要电子邮件地址在系统中是唯一的。所以,我想到使用电子邮件地址为主键。然而,我的同事认为字符串比较将比整数比较慢。
这是一个有效的理由不使用电子邮件为主键吗?
我们使用的是PostgreSQL。
与自动递增的数字相比,电子邮件地址是一个糟糕的初选候选人吗?
我们的web应用程序需要电子邮件地址在系统中是唯一的。所以,我想到使用电子邮件地址为主键。然而,我的同事认为字符串比较将比整数比较慢。
这是一个有效的理由不使用电子邮件为主键吗?
我们使用的是PostgreSQL。
当前回答
使用电子邮件地址作为主键的缺点:
Slower when doing joins. Any other record with a posted foreign key now has a larger value, taking up more disk space. (Given the cost of disk space today, this is probably a trivial issue, except to the extent that the record now takes longer to read. See #1.) An email address could change, which forces all records using this as a foreign key to be updated. As email address don't change all that often, the performance problem is probably minor. The bigger problem is that you have to make sure to provide for it. If you have to write the code, this is more work and introduces the possibility of bugs. If your database engine supports "on update cascade", it's a minor issue.
使用电邮地址作主键的优点:
You may be able to completely eliminate some joins. If all you need from the "master record" is the email address, then with an abstract integer key you would have to do a join to retrieve it. If the key is the email address, then you already have it and the join is unnecessary. Whether this helps you any depends on how often this situation comes up. When you are doing ad hoc queries, it's easy for a human being to see what master record is being referenced. This can be a big help when trying to track down data problems. You almost certainly will need an index on the email address anyway, so making it the primary key eliminates one index, thus improving the performance of inserts as they now have only one index to update instead of two.
在我看来,这两种情况都不是十拿九稳的。当有实用的键时,我倾向于使用自然键,因为它们更容易使用,而且在大多数情况下,缺点并不太重要。
其他回答
似乎没有人提到一个可能的问题,即电子邮件地址可能被视为隐私。如果电子邮件地址是主键,那么个人资料页面的URL很可能类似于..../Users/my@email.com。如果不想暴露用户的电子邮件地址怎么办?您必须找到其他一些识别用户的方法,可能是通过一个唯一的整数值来生成像..../Users/1这样的url。那么你最终会得到一个唯一的整数值。
这取决于桌子。如果表中的行表示电子邮件地址,那么电子邮件是最好的ID。如果不是,那么电子邮件不是一个好的ID。
您可能需要考虑任何适用的数据法规。电子邮件是个人信息,例如,如果你的用户是欧盟公民,那么根据GDPR,他们可以指示你从你的记录中删除他们的信息(记住,无论你在哪个国家,这都适用)。
如果出于参考完整性或审计等历史原因,需要将记录本身保存在数据库中,则使用代理键将允许您将所有个人数据字段设置为NULL。如果他们的个人数据是主键,这显然不那么容易
在逻辑层面上,电子邮件是天然的关键。 在物理层面上,如果您使用的是关系数据库,那么自然键并不适合作为主键。原因主要是别人提到的性能问题。
出于这个原因,设计可以进行调整。自然键成为替代键(UNIQUE, NOT NULL),您使用代理键/人工键/技术键作为主键,在您的情况下,这可以是一个自动递增键。
systempuntoout问道:
如果有人想更改他的电子邮件地址怎么办?你是否也要更改所有外键?
这就是级联的作用。
使用数字代理键作为主键的另一个原因与索引在平台中的工作方式有关。例如,在MySQL的InnoDB中,表中的所有索引都预先挂起了主键,所以你希望PK尽可能小(为了速度和大小)。同样与此相关的是,当主键按顺序存储时,InnoDB会更快,而字符串在那里没有帮助。
使用字符串作为替代键时要考虑的另一件事是,使用您想要的实际字符串的哈希值可能更快,跳过一些字母的大写和小写。(实际上,我降落在这里是为了寻找证据来证实我刚才说的话;还看……)
主键应该选择一个静态属性。由于电子邮件地址不是静态的,可以被多个候选人共享,因此使用它们作为主键并不是一个好主意。此外,电子邮件地址通常是一定长度的字符串,可能大于唯一id,我们想使用[len(email_address)>len(unique_id)],所以它将需要更多的空间,甚至最糟糕的是,它们被多次存储为外键。因此会导致性能下降。