数据表结构相关


一、数据类型及选用

1、数值类型

数值类型:存放数字型数据的约定,包括整数和小数。
数值类型数据:指字面值具有数学含义,能直接参加数值运算(例如求和、求平均值等)的数据。

(1)整数类型

整数类型主要用于存放整数数据。
不同的数据类型提供了不同的取值范围。
无符号整数类型都是从0开始,最大值一般是有符号类型最大值的两倍。

tinyint类型:小整数,数据类型用于保存一些范围的整数数值范围。
有符号:
-128 ~ 127
无符号:
0 ~ 255

CREATE TABLE `test`.`tinyint-test`  (
  `tinyint` tinyint(255) NULL,                        # 有符号
  `tinyint-unsigned` tinyint(255) UNSIGNED NULL       # 无符号
);

# 分别插入最小值
INSERT INTO `test`.`tinyint-test`(`tinyint`, `tinyint-unsigned`) VALUES (-128, 0);
# 分别插入最大值
INSERT INTO `test`.`tinyint-test`(`tinyint`, `tinyint-unsigned`) VALUES (127, 255)

smallint类型:大整数,两个字节。
有符号:
-32768 ~ 32767
无符号:
0 ~ 65535

CREATE TABLE `test`.`smallint-test`  (
  `smallint` smallint(255) NULL,
  `smallint-unsigned` smallint(255) UNSIGNED NULL
);
# 分别插入最小值
INSERT INTO `test`.`smallint-test`(`smallint`, `smallint-unsigned`) VALUES (-32768, 0);
# 分别插入最大值
INSERT INTO `test`.`smallint-test`(`smallint`, `smallint-unsigned`) VALUES (32767, 65535);

(2)小数类型

MySQL中用浮点数和定点数来表示小数。
浮点类型:单精度浮点类型(float)、双精度浮点类型(double)。
定点类型:decimal。
均使用(m,n)来表示,m表示总共的有效位数,n表示小数的位数。

此三种类型小数位最大值都是30,decimal的最大有效位数仅为65,float和double的最大有效位数是255。

# 验证精确度:decimal  >  double  > float.
# 均按最大值创建的表:
CREATE TABLE `test`.`float`  (
  `float` float(255, 30) NULL,
  `double` double(255, 30) NULL,
  `decimal` decimal(65, 30) NULL
);
INSERT INTO `test`.`float`(`float`, `double`, `decimal`) VALUES (1.111111111111111111111111111111, 1.111111111111111111111111111111, 1.111111111111111111111111111111);
mysql> select * from `float`;
+----------------------------------+----------------------------------+----------------------------------+
| float                            | double                           | decimal                          |
+----------------------------------+----------------------------------+----------------------------------+
| 1.111111164093017600000000000000 | 1.111111111111111200000000000000 | 1.111111111111111111111111111111 |
+----------------------------------+----------------------------------+----------------------------------+
1 row in set (0.00 sec)

# 四舍五入案例
CREATE TABLE `malldb`.`dec`  (
  `float` float(255, 7) NULL,         
  `double` double(255, 15) NULL,      
  `decimal` decimal(65, 30) NULL  
);
ALTER TABLE `malldb`.`dec` 
MODIFY COLUMN `float` float(10, 3) NULL DEFAULT NULL FIRST,
MODIFY COLUMN `double` double(12, 6) NULL DEFAULT NULL AFTER `float`,
MODIFY COLUMN `decimal` decimal(15, 12) NULL DEFAULT NULL AFTER `double`;

# 输入数据
INSERT INTO `malldb`.`dec`(`float`, `double`, `decimal`) VALUES (3.14159265253, 3.14159265253, 3.14159265253)

# 显示的结果
float   double      decimal
3.142	3.141593	3.141592652530

不管定点类型还是浮点类型,指定的精度超过精度范围,都会进行四舍五入。

2、字符串类型

主要存储字符串和文本信息。

(1)二进制字符串