与自动递增的数字相比,电子邮件地址是一个糟糕的初选候选人吗?

我们的web应用程序需要电子邮件地址在系统中是唯一的。所以,我想到使用电子邮件地址为主键。然而,我的同事认为字符串比较将比整数比较慢。

这是一个有效的理由不使用电子邮件为主键吗?

我们使用的是PostgreSQL。


当前回答

你的同事是对的:使用一个自动递增的整数作为你的主键。

您可以在应用程序级别实现电子邮件唯一性,或者您可以将电子邮件地址列标记为惟一,并在该列上添加索引。

将字段添加为唯一字段只会在插入到该表时花费字符串比较的成本,而不会在执行连接和外键约束检查时花费字符串比较成本。

当然,您必须注意,在数据库级别向应用程序添加任何约束都可能导致应用程序变得不灵活。在仅仅因为应用程序需要某个字段是唯一的或非空的,就将它设置为“唯一的”或“非空的”之前,一定要充分考虑。

其他回答

就我个人而言,我在设计数据库时不使用任何信息作为主键,因为我很可能在以后需要更改任何信息。我提供主键的唯一原因是,它方便从客户端执行大多数SQL操作,我的选择一直是自动增加整数类型。

不要使用电子邮件地址为主键,保持电子邮件的唯一性,但不要使用它为主键,使用用户id或用户名为主键

我对postgres不太熟悉。主键是一个很大的主题。我在这个网站(stackoverflow.com)上看到了一些很好的问题和答案。

我认为使用数字主键并在电子邮件列上使用UNIQUE INDEX可以获得更好的性能。电子邮件往往在长度上有所不同,可能不适合主键索引。

在这里和这里读点书。

我知道这有点晚了,但我想补充的是,人们放弃电子邮件帐户和服务提供商恢复地址,允许其他人使用它。

正如@HLGEM指出的那样,“Jsmith@somecompany.com很容易在一年后属于约翰·史密斯,两年后属于朱莉娅·史密斯。”在这种情况下,如果约翰·史密斯想要你的服务,你要么拒绝使用他的电子邮件地址,要么删除所有与朱莉娅·史密斯有关的记录。

如果你必须根据当地法律删除与企业财务历史有关的记录,你可能会发现自己陷入困境。

所以我永远不会使用电子邮件地址、车牌等数据作为主键,因为无论它们看起来多么独特,它们都不受你的控制,并且可能会提供一些你可能没有时间处理的有趣挑战。

使用电子邮件地址作为主键的缺点:

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.

在我看来,这两种情况都不是十拿九稳的。当有实用的键时,我倾向于使用自然键,因为它们更容易使用,而且在大多数情况下,缺点并不太重要。