时间:2021-07-01 10:21:17 帮助过:6人阅读
* MySQL支持SQL标准整数类型整数(或INT)和SMALLINT。作为标准的扩展,MySQL还支持整数类型TINYINT、MEDIUMINT和BIGINT
2. 整数类型所需的存储和值范围
类型 | 占用空间 | 最小值 | 最大值 |
(字节) | (signed/Unsigned) | (signed/Unsigned) | |
TINYINT | 1 | -128 | 127 |
0 | 255 | ||
SMALLINT | 2 | -32768 | 32767 |
0 | 65535 | ||
MEDIUMINT | 3 | -8388608 | 8388607 |
0 | 16777215 | ||
INT | 4 | -2147483648 | 2147483647 |
0 | 4294967295 | ||
BIGINT | 8 | -9223372036854775808 | 9223372036854775807 |
0 | 18446744073709551615 |
3. zerofill 属性遇到整数类型应用
* 创建zerofill测试表 zerofill_test
mysql> CREATE TABLE zerofill_test( -> `id` INT(6) ZEROFILL -> )ENGINE=INNODB CHARSET=utf8mb4; Query OK, 0 rows affected (0.08 sec)
* 插入数值长度小于6的值
mysql> INSERT INTO zerofill_test SELECT 11111; Query OK, 1 row affected (0.03 sec) Records: 1 Duplicates: 0 Warnings: 0
* 插入数值长度大于6的值
mysql> INSERT INTO zerofill_test SELECT 2222222; Query OK, 1 row affected (0.04 sec) Records: 1 Duplicates: 0 Warnings: 0
* 查看zerofill_test表所有的数据
mysql> SELECT * FROM zerofill_test; +---------+ | id | +---------+ | 011111 | | 2222222 | +---------+ 2 rows in set (0.01 sec)
* zerofill总结
* 当显示的值长度小于定义时INT定义的长度,高位补0显示
* 当显示的值长度大于定义时INT定义的长度,照常显示
* zerofill显示属性,值不做任何修改
4. Unsigned 类型溢出现象
* 创建unsigned测试表 unsigned_test
mysql> CREATE TABLE unsigned_test( -> id BIGINT PRIMARY KEY NOT NULL AUTO_INCREMENT, -> data INT UNSIGNED -> )ENGINE=INNODB CHARSET=utf8mb4; Query OK, 0 rows affected (0.12 sec)
* 插入两行一大一小的值
mysql> INSERT INTO unsigned_test SELECT null, 1; Query OK, 1 row affected (0.03 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> INSERT INTO unsigned_test SELECT null, 2; Query OK, 1 row affected (0.01 sec) Records: 1 Duplicates: 0 Warnings: 0
* 查看表中插入的数据值
mysql> SELECT * FROM unsigned_test; +----+------+ | id | data | +----+------+ | 1 | 1 | | 2 | 2 | +----+------+ 2 rows in set (0.00 sec)
* 利用小数值对大数值做减运算
mysql> SELECT data - (SELECT data FROM unsigned_test where id=2) FROM unsigned_test where id=1; ERROR 1690 (22003): BIGINT UNSIGNED value is out of range in ‘(`mytest`.`unsigned_test`.`data` - (select `mytest`.`unsigned_test`.`data` from `mytest`.`unsigned_test` where 1))‘
5. 整数类型应用总结
* signed/Unsigned: 是否有符号
* ZEROFILL: 显示属性,值不做任何修改
* 推荐不要使用UNSIGNED, 范围本质上没有大的改变
* UNSIGNED可能会有溢出现象发生
* 自增INT 类型主键建议使用BIGINT
6. 总结
以需求驱动技术,技术本身没有优略之分,只有业务之分。
本文出自 “sea” 博客,请务必保留此出处http://lisea.blog.51cto.com/5491873/1943195
MySQL数据类型--------整数类型实战
标签:mysql dba 数据类型