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

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

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

我们使用的是PostgreSQL。


当前回答

使用GUID作为主键…这样,当你执行INSERT操作时,你就可以从程序中生成它,而不需要从服务器获取响应来找出主键是什么。它在所有表和数据库中都是唯一的,如果有一天你截断了表,自动增量被重置为1,你不必担心会发生什么。

其他回答

这取决于桌子。如果表中的行表示电子邮件地址,那么电子邮件是最好的ID。如果不是,那么电子邮件不是一个好的ID。

整数主键更好的另一个原因是当您在不同的表中引用电子邮件地址时。如果address本身是一个主键,那么在另一个表中你必须使用它作为一个键。所以你可以多次存储电子邮件地址。

这很糟糕。假设某个电子邮件提供商倒闭了。用户会想要更改他们的电子邮件。如果你使用e-mail作为主键,用户的所有外键都将复制该电子邮件,这使得更改它非常困难……

... 我甚至还没有开始谈论性能考虑因素。

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

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.

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

如果只是要求电子邮件是唯一的,那么你可以用该列创建一个唯一的索引。