The difference between int(1) and int(10)

The difference between int(1) and int(10)

Recently, I encountered a problem. There is a table that needs to add a user_id field. The user_id field may be very large, so I submitted a mysql work order: alter table xxx ADD user_id int(1). The leader saw my SQL work order, so he said: I'm afraid this int(1) is not enough. The next step is to explain.

In fact, this is not the first time I have encountered such a problem, and there are many experienced drivers who have worked for more than 5 years. Including that I often see my colleagues using int(10) all the time. I feel that if int(1) is used, the upper limit of the field is limited. This is definitely not the case.

We know that in mysql, int occupies 4 bytes, so for unsigned int, the maximum value is 2^32-1 = 4294967295, which is nearly 4 billion. Can't this maximum value be reached by using int(1)?

CREATE TABLE `user` (
  `id` int(1) unsigned NOT NULL AUTO_INCREMENT,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

The id field is an unsigned int(1). Let me insert a maximum value to see.

mysql> INSERT INTO user (id) VALUES (4294967295);
Query OK, 1 row affected ( 0.00 sec)
You can see that it is successful, which means that the number after int does not affect the size supported by int itself. There is no difference between int(1), int(2)...int(10).

3 Zero filling
Generally, the number after int is only effective when used with zerofill. Let’s look at an example first:

CREATE TABLE `user` (
  `id` int(4) unsigned zerofill NOT NULL AUTO_INCREMENT,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;

Note that a zerofill is added after int(4). Let’s insert 4 pieces of data first.

mysql> INSERT INTO `user` (`id`) VALUES (1),(10),(100),(1000);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

Insert 4 pieces of data: 1, 10, 100, and 1000 respectively, and then let’s query:

mysql> select * from user;
+------+
| id   |
+------+
| 0001 |
| 0010 |
| 0100 |
| 1000 |
+------+

4 rows in set (0.00 sec)

Through the data, we can find that int(4) + zerofill realizes the phenomenon of filling 0 with less than 4 bits, and int(4) alone is useless.

And for 0001, the underlying storage is still 1, but the displayed one will be filled with 0.

Summary
The number after int cannot represent the length of the field. Zerofill is generally added to int(num) to have an effect. The function of zerofill can generally be used in some number-related numbers, such as student numbers 001 002...999. If mysql does not have the zero-fill function, but you want to format and output equal-length numbers, then you only need to I can handle it myself.
Insert image description here

Supongo que te gusta

Origin blog.csdn.net/weixin_45817985/article/details/134877425
Recomendado
Clasificación