MySQL 布尔值“tinyint(1)”最多可保存 127 个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4401673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySQL Boolean "tinyint(1)" holds values up to 127?
提问by JD Isaacks
I wanted to make a true/false field for if an item is in stock.
我想为某件商品是否有库存制作一个真/假字段。
I wanted to set it to Boolean ( which gets converted to tinyint(1)
), 1 for in stock, 0 for not in stock.
我想将它设置为布尔值(转换为tinyint(1)
),1 表示有货,0 表示没有库存。
I am getting feeds from vendors, so I thought to myself, "What if they pass how many are instock?"
我从供应商那里获得提要,所以我心里想,“如果他们通过了多少库存呢?”
So I wondered if I inserted a number higher than 1 what would happen. I assumed it would default to 1.
所以我想知道如果我插入一个大于 1 的数字会发生什么。我认为它会默认为 1。
To my surprise it will allow me to hold any number up to 127, anything over defaults to 127.
令我惊讶的是,它允许我保存最多 127 的任何数字,超过默认值的任何数字为 127。
Can anyone explain why?
谁能解释为什么?
回答by BoltClock
The signed TINYINT
data type can store integer values between -128 and 127.
有符号TINYINT
数据类型可以存储 -128 到 127 之间的整数值。
However, TINYINT(1)
does not change the minimum or maximum value it can store. It just says to displayonly one digit when values of that type are printed as output.
但是,TINYINT(1)
不会更改它可以存储的最小值或最大值。它只是说当该类型的值作为输出打印时只显示一位。
回答by Nathan
The tinyint
data type utilizes 1 byte of storage. 256 possible integer values can be stored using 1 byte (-128 through 127). if you define as tinyint unsigned
then negative values are discarded so is possible to store (0 through 255).
该tinyint
数据类型利用存储的1个字节。使用 1 个字节(-128 到 127)可以存储 256 个可能的整数值。如果您定义为,tinyint unsigned
那么负值将被丢弃,因此可以存储(0 到 255)。
回答by mdm
See herefor how MySQL handles this. If you use MySQL > 5.0.5 you can use BIT
as data type (in older versions BIT
will be interpreted as TINYINT(1)
. However, the (1)
-part is just the display width, not the internal length.
请参阅此处了解 MySQL 如何处理此问题。如果您使用 MySQL > 5.0.5,您可以使用BIT
as 数据类型(在旧版本BIT
中将被解释为TINYINT(1)
。但是,(1)
-part 只是显示宽度,而不是内部长度。
回答by Rabeel Javed
CREATE TABLE foo_test(
col_1 TINYINT
, col_2 TINYINT(2)
, col_3 TINYINT(3)
, col_4 TINYINT(2) ZEROFILL
, col_5 TINYINT(3) ZEROFILL
);
INSERT INTO foo_test( col_1,col_2,col_3,col_4,col_5 )
SELECT 1, 1,1,1,1
UNION ALL
SELECT 10, 10,10,10,10
UNION ALL
SELECT 100, 100,100,100,100;
SELECT * FROM foo_test;
**OUTPUT:-**
col_1 col_2 col_3 col_4 col_5
------ ------ ------ ------ --------
1 1 1 01 001
10 10 10 10 010
100 100 100 100 100
MySQL will show the 0's in the start if zerofillis used while creating the table. If you didn't use the zerofillthen it is not effective.
如果在创建表时使用zerofill,MySQL 将在开头显示 0 。如果您没有使用zerofill,则它无效。