只要做開發的,肯定創建過表,表字段用什麼類型,長度是多少等。感覺沒什麼要說的,可是歸納總結一下,還有東西可說的。
知道類型的范圍值對我們有幫助的,例如,如果用tinyint,該字段的最大值不會超過255,把字段設置成tinyint(10),有符號的情況下,最大只能是127,表面上看好像是可以存入10位,而實際只能存入3位數。
根據要存數字大小,來選擇不同的數據類型,例如,如果是標識位,一般情況設置為tinyint(1),最合適,存儲小,又不會存不進去。
MariaDB [test]> CREATE TABLE `test` (
-> `big_test` bigint(20) DEFAULT 0,
-> `int_test` int(11) DEFAULT 0,
-> `medium_test` mediumint(8) DEFAULT 0,
-> `small_test` smallint(6) DEFAULT 0,
-> `tiny_test` tinyint(4) DEFAULT 0
-> ) ENGINE=myisam DEFAULT CHARSET=utf8;
Query OK, 0 rows affected (0.09 sec)
MariaDB [test]> INSERT INTO test (big_test, int_test, medium_test, small_test, tiny_test) VALUES (9223372036854775807, 2147483647, 8388607, 32767, 127);
Query OK, 1 row affected (0.00 sec)
MariaDB [test]> select * from test;
+---------------------+------------+-------------+------------+-----------+
| big_test | int_test | medium_test | small_test | tiny_test |
+---------------------+------------+-------------+------------+-----------+
| 9223372036854775807 | 2147483647 | 8388607 | 32767 | 127 |
+---------------------+------------+-------------+------------+-----------+
1 row in set (0.00 sec)
MariaDB [test]> INSERT INTO test (big_test, int_test, medium_test, small_test, tiny_test) VALUES (9223372036854775807, 2147483647, 8388607, 32767, 128);
Query OK, 1 row affected, 1 warning (0.00 sec) //128超過了,有符號tinyint的最大值,報了warning出來,但是還是入庫了。
MariaDB [test]> select * from test;
+---------------------+------------+-------------+------------+-----------+
| big_test | int_test | medium_test | small_test | tiny_test |
+---------------------+------------+-------------+------------+-----------+
| 9223372036854775807 | 2147483647 | 8388607 | 32767 | 127 |
| 9223372036854775807 | 2147483647 | 8388607 | 32767 | 127 |
+---------------------+------------+-------------+------------+-----------+
2 rows in set (0.00 sec)
MariaDB [test]> ALTER TABLE `test` CHANGE `tiny_test` `tiny_test` TINYINT( 10 ) NULL DEFAULT Ɔ'
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0 //將長度改為10,沒報錯
MariaDB [test]> INSERT INTO test (big_test, int_test, medium_test, small_test, tiny_test) VALUES (9223372036854775807, 2147483647, 8388607, 32767, 128);
Query OK, 1 row affected, 1 warning (0.00 sec) //在插入數據,一樣報warning,但還是入庫
MariaDB [test]> select * from test;
+---------------------+------------+-------------+------------+-----------+
| big_test | int_test | medium_test | small_test | tiny_test |
+---------------------+------------+-------------+------------+-----------+
| 9223372036854775807 | 2147483647 | 8388607 | 32767 | 127 |
| 9223372036854775807 | 2147483647 | 8388607 | 32767 | 127 |
| 9223372036854775807 | 2147483647 | 8388607 | 32767 | 127 |
+---------------------+------------+-------------+------------+-----------+
3 rows in set (0.00 sec)