在 MySQL 中使用 INT(1) 与 TINYINT(1) 有没有区别?


括号中使用的数字 1 仅用于显示宽度。INT(1) 和 TINYINT(1) 不影响存储。

TINYINT 占 1 字节,这意味着其范围为 -128 至 +127,而 int 占 4 字节;其范围为 -2147483648 至 +2147483647

为了理解宽度显示,让我们创建一个表 -

mysql> create table intAndTinyint
   −> (
   −> FirstNumber int(1) zerofill,
   −> SecondNumber tinyint(1) zerofill
   −> );
Query OK, 0 rows affected (0.52 sec)

现在,您可以在表中插入记录。查询如下 -

mysql> insert into intAndTinyint values(1,1);
Query OK, 1 row affected (0.32 sec)

mysql> insert into intAndTinyint values(12,12);
Query OK, 1 row affected (0.26 sec)

mysql> insert into intAndTinyint values(123,123);
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示表中的所有记录。查询如下 -

mysql> select *from intAndTinyint;

以下是输出 -

+-------------+--------------+
| FirstNumber | SecondNumber |
+-------------+--------------+
|           1 |            1 |
|          12 |           12 |
|         123 |          123 |
+-------------+--------------+
3 rows in set (0.00 sec)

当括号中的数字 1 使用填充零增加到 1 以上时,您就会理解这一点。让我们只看一个 INT 的示例以了解宽度填充零的概念。

创建一个表。以下是创建表的查询 -

mysql> create table intVsIntAnyThingDemo
   −> (
   −> Number1 int(11) unsigned zerofill,
   −> Number int(13) unsigned zerofill
   −> );
Query OK, 0 rows affected (1.17 sec)

现在,您可以在表的帮助下使用 insert 命令插入记录。在这里,我们为 INT 设置了不同的宽度。查询如下 -

mysql> insert into intVsIntAnyThingDemo values(12345,6789);
Query OK, 1 row affected (0.44 sec)

mysql> insert into intVsIntAnyThingDemo values(3,2);
Query OK, 1 row affected (0.20 sec)

mysql> insert into intVsIntAnyThingDemo values(12,89);
Query OK, 1 row affected (0.15 sec)

mysql> insert into intVsIntAnyThingDemo values(123,6789);
Query OK, 1 row affected (0.17 sec)

mysql> insert into intVsIntAnyThingDemo values(1234,6789);
Query OK, 1 row affected (0.14 sec)

使用 select 语句显示所有记录。查询如下 -

mysql> select *from intVsIntAnyThingDemo;

以下是显示不同宽度和填充零的输出

+-------------+---------------+
| Number1     | Number        |
+-------------+---------------+
| 00000012345 | 0000000006789 |
| 00000000003 | 0000000000002 |
| 00000000012 | 0000000000089 |
| 00000000123 | 0000000006789 |
| 00000001234 | 0000000006789 |
+-------------+---------------+
5 rows in set (0.00 sec)

更新于: 30-Jul-2019

2K+ 浏览次数

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.