您的位置:首页 > 数据库 > MySQL

【MySQL数据类型1之--数值类型】

2010-05-13 21:21 603 查看
MySQL基本数值类型大致可以分成:
整数类型:TINYINT、SAMLLINT、MEDIUMINT、INT、BIGINT--1字节、2、3.、4、8
浮点数类型:FLOAT(m,d)、DOUBLE(m,d)==REAL-4字节、8
定点数类型:DECIMAL(m,d)、NUMERIC-m+2字节、8
位类型:BIT(m)-1-8字节
各个类型的详细范围可以参考mysql文档


数据类型小例:
1.整数类型
create table t1
(
id int,
id2 int(4)
);
insert t1 select 1,2;
select * from t1;
+------+------+
| id | id2 |
+------+------+
| 1 | 2 |
+------+------+
alter table t1 modify id int zerofill;
alter table t1 modify id2(4) int zerofill;
select * from t1;
+------------+------------+
| id | id2 |
+------------+------------+
| 0000000001 | 0002 |
+------------+------------+
insert t1 select 1,11111;
Select * from t1;
+------------+------------+
| id | id2 |
+------------+------------+
| 0000000001 | 0002 |
| 0000000001 | 11111 |
+------------+------------+
insert t1 select -1,-2;
+-------+------+---------------------------------------------+
| Level | Code | Message |
+-------+------+---------------------------------------------+
| Error | 1264 | Out of range value for column 'id' at row 1 |
+-------+------+---------------------------------------------+

结论:
1. INT类型默认宽度11
2上面的zerofill属性可以在int指定宽度不足时候在前面补上0
3.在插入的数值实际长度超过INT类型指定宽度时,忽略宽度,插入正确数值;
4.在拥有zerofill属性后的int字段自动加上属性UNSIGNED,范围从0开始



2.小数类型
小数分成浮点数和定点数。浮点数包括单精度的FLOAT和双精度的DOUBLE;定点数则在内部以字符串形式存放,比较是和货币等高精度数据。
小数类型后面的(m,d)前者表示数字共有m个数字(整数+小数位),小数点后面有d个数字位。
create table t2
(
col1 float(5,2),
col2 decimal(5,2)
);
insert t2 select 1.11,1.11;
select * from t2;
+------+------+
| col1 | col2 |
+------+------+
| 1.11 | 1.11 |
+------+------+
insert t2 select 1.225,1.225;
select * from t2;
+------+------+
| col1 | col2 |
+------+------+
| 1.11 | 1.11 |
| 1.23 | 1.23 |
+------+------+
alter table t2 modify col1 float;
alter table t2 modify col2 decimal;
select * from t2;
+------+------+
| col1 | col2 |
+------+------+
| 1.11 | 1 |
| 1.23 | 1 |
| 1.11 | 1 |
+------+------+
insert t2 select 1.611111,1.6111111;
select * from t2;
+---------+------+
| col1 | col2 |
+---------+------+
| 1.11 | 1 |
| 1.23 | 1 |
| 1.11 | 1 |
| 1.61111 | 2 |
+---------+------+

结论:
1.指定了小数位数后,如果插入的数的小数位数超过,会自动截断,并且四舍五入;
2.修改小数位数后,decima会对现有数据进行自动截断,以符合现在的数据类型;
3.默认的decimal的m,d分别为10和0 也就是默认整形;



3.bit数值类型
Bit(m)中m的范围从1-64 默认为1。
create table t3
(
col bit(1)
);
insert t3 select 2;
+-------+------+-----------------------------------------+
| Level | Code | Message |
+-------+------+-----------------------------------------+
| Error | 1406 | Data too long for column 'col' at row 1 |
+-------+------+-----------------------------------------+
alter table t3 modify col bit(6);
insert t3 select 2;
select * from t3;
+------+
| col |
+------+
| |
+------+
select BIN(col),hex(col) from t3 ;
+----------+----------+
| BIN(col) | hex(col) |
+----------+----------+
| 10 | 2 |
+----------+----------+

结论:
1.插入bit字段数值时,首先会把值转成2进制;如果位数比自定的长度大,插入失败;
2.直接显示bit类型数据,结果为null;需要使用 bin()或者hex()等函数转化后显示;

参考:MySQL5权威指南+深入浅出MySQL(网易)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: