自动递增的主键

自动递增的主键

问题描述:

自动递增主键(使用int数据类型)适用于表格或者我们的用户定义主键最适合数据库中的表格以便更好地管理。

请指定我。

Is auto incremented primary key (with int datatype) is good for for a table OR our user-defined primary key is best for a table in a database for better management.
Please specify me.

最好为您的表使用 INT 主键(自动增量)加入等,并由系统优化性能。



您可能还需要一个用户键,您将向用户显示该键并将用于在高级别搜索。
It is better to have a INT primary key (auto increment) for your tables which you use for joins etc. and are optimized by the system for performance.

You will probably need a "user" key also which you will show to your users and will be used for searching at a high level.


如果你关心删除/缺少键值,那么Identity不适合你。查看我过去的答案了解更多详情。 重新使用自动递增的主键 [ ^ ]



基于上述原因,Identity不用于显示目的。出于内部目的,身份是好的。



身份字段就像索引,不能用于搜索。



当您需要像EmployeeID这样的非数字值时,用户定义的键很有用。 (例如EMP0005)。因此,在搜索过程中,我们可以使用此值来提供特定员工的详细信息。



所以答案取决于。
If you care deleted/missing key values then Identity is not for you. Check my past answer for more details. Re using an auto incremented primary key[^]

Based on above mentioned reason, Identity is not for display purpose. For internal purpose, Identity is good one.

Identity field is just like Index, not suggestible for searching.

User defined keys are useful when you need non-numeric values like EmployeeID. (Ex. EMP0005). So during search, we could use this value to bring particular Employee's details.

So the answer is Depends.


从基础的。什么是主键?它是一个在表中唯一标识行的键。因此,我们了解主键的每个字段都应该是唯一的。这是第一个条件。要实现这一点,您可以使用Identity列或Sequence(sql server 2012)。对于这两种类型,您应该声明字段数据类型int,bigint。您也可以使用guid作为主键。如果您将来确实需要将数据转到数据仓库,那么请考虑guid是第一优先。在所有这些情况下,数据库系统/应用程序为您生成独特的价值。

您还可以创建自定义唯一值。但主要的挑战是并发处理。所以最好不要使用自定义代码来处理并发,而是依赖于经过验证的系统。

所以我认为你可以依靠系统生成主键。
Start from the basic. What is primary key? It is a key which identify rows uniquely in a table. So we understand that each field of primary key should be unique. It is first condition. To achieve that you can use Identity column or Sequence(sql server 2012). For both type you should declare your field data type int, bigint. You can also use guid as a primary key. If you really need in future your data will go to datawarehouse then consider guid is the first priority. in all that cases database system/application generate unique value for you.
You can also create custom unique value. But the main challenge on that is concurrency handling. So it is better instead of handling concurrency with custom code you can depend on proven system.
So my opinion is you can depend on system for generate primary key.