MySQL 中的 `unsigned` 是什么意思以及何时使用它?

2021-12-25 00:00:00 types mysql

无符号"在 MySQL 中是什么意思,我什么时候应该使用它?

What does "unsigned" mean in MySQL and when should I use it?

推荐答案

MySQL 说:

所有整数类型都可以有一个可选的(非标准)属性 UNSIGNED.无符号类型可用于允许一列中只有非负数或 当您需要更大的鞋面时列的数值范围.为了例如,如果一个 INT 列是 UNSIGNED,列范围的大小是相同,但它的端点从-2147483648 和 2147483647 到 0 和 4294967295.

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

我什么时候使用它?

问自己这个问题:这个字段会包含负值吗?
如果答案是否定的,那么您需要 UNSIGNED 数据类型.

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

一个常见的错误是使用从零开始的自增INT的主键,但类型是SIGNED,在这种情况下,您将永远不会触及任何负数,并且您正在将可能的 id 范围减少到一半.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

相关文章