一、整型( int, tinyint, smallint 等 ) #創建表CREATE TABLE t1 (num TINYINT)CHARSET utf8 ENGINE MYISAM;#添加一列num2,類型為tinyint, 屬性為unsignedALTER TABLE t1 ADD num2 ...
一、整型( int, tinyint, smallint 等 )
------------------------------------------------------------------------------------------------------------------------------------------------------
#創建表
CREATE TABLE t1 (
num TINYINT
)CHARSET utf8 ENGINE MYISAM;
#添加一列num2,類型為tinyint, 屬性為unsigned
ALTER TABLE t1 ADD num2 TINYINT UNSIGNED;
#添加一列num3,類型為tinyint, 屬性為zerofill填充, 寬度為4,這個4,並不是限制範圍的
ALTER TABLE t1 ADD num3 TINYINT( 4 ) ZEROFILL;
#增加一列num4,類型為int,寬度為4
ALTER TABLE t1 ADD num4 TINYINT( 4 );
#把num4的列類型,改成int
ALTER TABLE t1 MODIFY num4 INT( 4 );
#欄位最大值( 溢出 )測試
INSERT INTO t1 VALUES( 200 );
INSERT INTO t1 VALUES( -128 );
INSERT INTO t1 VALUES( -129 );
INSERT INTO t1 VALUES( -1, 200 );
INSERT INTO t1 VALUES( -1, 256 );
INSERT INTO t1 VALUES( -128, -1, 2 );
二、浮點型( float, double, decimal )
------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE TABLE t2(
num FLOAT( 6, 2 )
)CHARSET utf8 ENGINE MYISAM;
#num FLOAT( 6, 2 ), 6表示最大的位數,2表示小數點位數,所以他能表示的最大值為9999.99
INSERT INTO t2 VALUES( 1234.56 );
#下麵12340溢出,這個位置最大隻能存9999
INSERT INTO t2 VALUES( 12340 );
註意:float與double有精度損失, decimal是定點型,不會損失精度
三、字元型( char, varchar, text, enum 等 )
------------------------------------------------------------------------------------------------------------------------------------------------------
char型如果不夠M個字元,後面用空格補齊,取出時,把右邊的空格去掉
註意:這表明,如果數據本身右側有空格,將會丟失
#char型與varchar型測試
CREATE TABLE t3 (
n1 CHAR( 10 ),
n2 VARCHAR( 10 )
)CHARSET utf8 ENGINE MYISAM;
INSERT INTO t3 VALUES( ' ghostwu ', ' ghostwu ' );
select concat( '(', n1, ')' ), concat( '(', n2, ')' ) from t3;
從下圖可知:n1列存儲的值,由於是定長,取出來的時候,右邊的空格丟失了
CREATE TABLE t4(
gender ENUM( '男', '女' )
)CHARSET utf8 ENGINE MYISAM;
INSERT INTO t4 VALUES( '男' );
INSERT INTO t4 VALUES( '女' );
#man不在枚舉範圍內,插入不了
INSERT INTO t4 VALUES( 'man' );
四、時間類型測試( year, time, date, datetime, timestamp, unsigned int )
------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE TABLE t5(
t1 YEAR,
t2 TIME,
t3 DATE,
t4 DATETIME,
t5 TIMESTAMP
) CHARSET utf8 ENGINE MYISAM;
INSERT INTO t5( t1 ) VALUES( '32' );
INSERT INTO t5( t1 ) VALUES( '1932' );
INSERT INTO t5( t1 ) VALUES( '2032' );
INSERT INTO t5( t1, t2, t3, t4 ) VALUES( '2100', '20:02:34', '2018-03-12', '2018-03-12 20:02:34' );
註:一般時間都用int型存儲,便於計算,timestamp類型會自動插入當前的時間