mysql有符号和无符号,MySQL中的“无符号”是什么意思以及何时使用它?

时间:2025-03-17 08:50:05

MySQL中的“无符号”是一种数据类型。每当我们在任何列中写入无符号表示您不能插入负数时。假设对于很大的数字,您可以使用无符号类型。

无符号整数的最大范围是4294967295。Note: If you insert negative value you will get a MySQL error.

这是无符号类型的示例演示。让我们首先创建一个带有“ unsigned”列的表。以下是创建表的查询-create table UnsignedDemoWithPositiveValue

-> (

-> Distance int unsigned

-> );

如果尝试使用无符号4294967295插入较高的值,则由于该值超出范围,将产生错误。

插入超出范围的值。insert into UnsignedDemoWithPositiveValue values(4294967296);

ERROR 1264 (22003): Out of range value for column 'Distance' at row 1

在上面的示例中,我插入了4294967296,它超出范围,因此会产生错误。

现在,我将另一个值4294967295插入表中。insert into UnsignedDemoWithPositiveValue values(4294967295);

在上面,您可以看到查询已成功执行。

现在,让我们来看另一个例子。如果插入否定记录,则可以看到以下错误-insert into UnsignedDemoWithPositiveValue values(-124);

ERROR 1264 (22003): Out of range value for column 'Distance' at row 1

我现在将仅插入值为124的正值。查询如下-insert into UnsignedDemoWithPositiveValue values(124);

如上所示,查询已成功执行。

让我们借助select语句显示记录。查询如下-select *from UnsignedDemoWithPositiveValue;

这是输出-+------------+

| Distance   |

+------------+

| 4294967295 |

| 124        |

+------------+

2 rows in set (0.00 sec)