1

我必须存储可以是十进制格式的用户积分,例如(10.99、0.99 等)。现在我将列字段作为 varchar(100)。

如果我使用十进制而不是 varchar 怎么办?会提高性能吗??

4

3 回答 3

10

简短的回答是:不,它会损害性能。

更长的答案:VARCHAR 字段是可变长度的,这意味着数据库块的格式不能预先考虑填充在那里的数据的大小。当然,有一个字段的最大长度,但除此之外,你的情况更糟。

另一方面,读取 VARCHAR 然后将其解释为适合浮点类型会花费您。它引入了新的问题可能性。尝试获取占“11.99”的所有小数。希望你带来正确的小数位数,因为在 VARCHAR "11.99" != "11.990" 中。

然后是索引。通常,没有人为十进制字段编制索引,但如果您这样做,VARCHAR 字段上的索引将需要更多空间。

总而言之,将某些内容保存在非特定字段类型中并不是一个好主意。在 DB 结构中,通常认为最佳实践尽可能具体。

于 2013-04-15T19:00:32.067 回答
3

Suprisingly, you can save disk space (and thus IO time) this way. It really depends on what the decimal values are and if they're going to stay within that range, and you should absolutely check before doing it.

select 
  sum(1+len(cast(Cast(your_decimal_value as real) as varchar(50)))) as size_as_varchar,
  size_of_your_decimal_type_in_bytes*count(*) as size_as_decimal
from your_table

If size_as_varchar is substantially lower than size_as_decimal, then you may see performance gains for IO bound queries. The casting CPU cost may cancel out the gains.

So, should you do this? It depends on your server, your data, how many of these values your queries require casting on, and your boss' tolerence for deviances from best practice... but the answer is probably no. If you need this, you should use a database that provides row level compression instead of doing hacky things to approximate row level compression.

于 2013-05-29T18:58:22.290 回答
1

在某些情况下,您可能希望将看起来像数字的值存储为字符串。例如,在美国,5 位数的邮政编码看起来很像数字。但是,前导零很重要。因此,它们实际上是标签而不是数字。这很简单;邮政编码应存储为字符串。

在大多数其他情况下,您希望将数字存储为数字。一个名为“用户积分”的字段表明您正在该字段上进行加法和减法。所以,这也是不言而喻的。如果看起来像数字,走路像数字,嘎嘎声像数字。. . 将其存储为数字。

MySQL 确实使选择有点混乱,因为它会自动将字符串转换为数字,即使字符串在数字部分后面有无关字符。

If you want the second decimal point stored exactly, then use a fixed-point data type (such as DECIMAL(5,2)) rather than a floating point type (such as float).

于 2013-04-15T19:01:33.860 回答