SQLServer选择主键类型
我有一个对象列表,每个对象都有自己的 id,我需要在数据库中为它们创建一个表。使用它们的 id(因为它们是唯一的)作为表中的主键是个好主意,但有一个问题。除一个对象外,所有 id 均为整数 - 它有 2 个子对象,id 分别为 142.1
和 142.2
,因此 id 列表为 140、141、142.1、142.2, 143...
现在,如果我选择 double 作为主键类型,那么它将存储不必要的 6 个字节(因为 double 是 8 个字节,INT
是 2),仅支持两个 double 数字,我不能选择 <代码>INT。那么,如果我无法更改对象列表,我应该使用什么类型呢?
I have a list of objects each of its own id and I need to create a table for them in a database. It's a good idea to use their ids(since they are unique) as a primary key in the table but there's one problem. All ids are integers except for the one object - it has 2 subobjects with ids 142.1
and 142.2
, so the id list is 140, 141, 142.1, 142.2, 143...
Now if I choose a double as a type of primary key then it will store unnecessary 6 bytes(since double is 8 bytes and INT
is 2) to only support two double numbers and I can't choose INT
. So what type should I use if I cannot change the list of objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
double
的数学是不精确,你不应该将它用于离散诸如金钱或对象 ID 之类的数字。考虑使用十进制(p,s)
反而。其中p
是总位数,s
是点后面的位数。例如,decimal(5,2)
可以存储123.45
,但不能存储1234
或12.345
。另一种选择是两个整数 n1, n2 的复合主键:
The math for
double
is imprecise, you shouldn't use it for discrete numbers like money or object id's. Consider usingdecimal(p,s)
instead. Wherep
is the total number of digits, ands
is the number of digits behind the dot. For example, adecimal(5,2)
could store123.45
, but not1234
or12.345
.Another option is a composite primary key for two integers
n1, n2
:int
是四个字节,而不是两个,因此与 double 的大小差异并没有那么大。但是,您绝对不应该使用浮点数作为键,因为浮点数不是存储为精确值,而是存储为近似值。
您可以使用带有一位小数位的
decimal
(例如decimal(5,1)
)来存储类似的值。decimal
是一个定点数,因此它存储为精确值,而不是近似值。An
int
is four bytes, not two, so the size difference to a double is not so big.However, you should definitely not use a floating point number as key, as a floating point number isn't stored as an exact values, but as an approximation.
You can use a
decimal
with one fractional digit, likedecimal(5,1)
, to store a value like that. Adecimal
is a fixed point number, so it's stored as an exact value, not an approximation.选择适当长度的
VARCHAR
和CHECK
约束,以确保数据符合您的域规则,例如基于您发布的小样本数据:Choose
VARCHAR
of an appropriate length, withCHECK
constraints to ensure the data conforms to your domain rules e.g. based on the small sample data you posted: