Mysql 简明教程
MySQL - TINYINT
The MySQL TINYINT Data Type
MySQL TINYINT 数据类型用于将整数值存储在非常小的范围内。它仅占用 1 字节(8 位)存储,对于有符号的 TINYINT 来说可以容纳 -128 到 127 的值,对于无符号的 TINYINT 来说可以容纳 0 到 255 的值。
The MySQL TINYINT data type is used to store integer values within a very small range. It occupies just 1 byte (8 bits) of storage and can hold values from -128 to 127 for signed TINYINT or 0 to 255 for unsigned TINYINT.
当你在 MySQL 中定义一个 TINYINT 列时,默认情况下它被认为是有符号的。这意味着它可以在特定范围内容纳正数和负数。此外,你可以使用“TINYINT”或“INT1”来定义这种列,因为它们以相同的方式工作。
When you define a TINYINT column in MySQL, by default it is considered as SIGNED. This means it can hold both positive and negative numbers within a specific range. Additionally, you can use either "TINYINT" or "INT1" to define such a column because they work the same way.
Syntax
以下是 MySQL TINYINT 数据类型的语法 -
Following is the syntax of the MySQL TINYINT data type −
TINYINT(M) [SIGNED | UNSIGNED | ZEROFILL]
Example
首先,让我们使用以下查询创建一个名为 tinyint_table 的表 -
First, let us create a table with the name tinyint_table using the below query −
CREATE TABLE tinyint_table (
col1 TINYINT,
col2 TINYINT UNSIGNED,
col3 TINYINT ZEROFILL
);
以下是所获得的输出 −
Following is the output obtained −
Query OK, 0 rows affected, 1 warning (0.03 sec)
现在,让我们尝试将某些值(128、128、128)插入这些列,如下所示 -
Now, let us try to insert some values (128, 128, 128) into these columns as shown below −
INSERT INTO tinyint_table VALUES (128, 128, 128);
col1 中的值会生成错误,因为我们插入的值超出了范围 -
An error is generated for the value in col1 because the value we inserted is out of range −
ERROR 1264 (22003): Out of range value for column 'col1' at row 1
接下来,如果我们尝试在 TINYINT UNSIGNED 列 (“col2”) 中插入一个负值,它将导致错误,因为 UNSIGNED 值不能是负数 -
Next, if we try to insert a negative value into the TINYINT UNSIGNED column ("col2"), it will result in an error because UNSIGNED values cannot be negative −
INSERT INTO tinyint_table VALUES (127, -120, 128);
显示的错误信息如下 -
The error message displayed is as follows −
ERROR 1264 (22003): Out of range value for column 'col2' at row 1
同样,如果我们将 -128 插入 TINYINT ZEROFILL 列 (“col3”),系统会生成一个错误 −
Similarly, if we insert -128 into the TINYINT ZEROFILL column ("col3"), an error will be generated −
INSERT INTO tinyint_table VALUES (127, 128, -128);
输出如下所示:
The output is as shown below −
ERROR 1264 (22003): Out of range value for column 'col3' at row 1
但是,如果我们插入有效范围内的值,插入操作会成功,如下所示 −
However, if we insert values within the valid range, the insertion will succeed as shown below −
INSERT INTO tinyint_table VALUES (127, 128, 128);
以下是上面代码的输出: -
Following is the output of the above code −
Query OK, 1 row affected (0.01 sec)
最后,我们可以使用以下 SELECT 查询检索表中所有已有的记录 −
Finally, we can retrieve all the records present in the table using the following SELECT query −
SELECT * FROM tinyint_table;
该查询将显示以下结果 −
This query will display the following result −