postgresql 如何在 ALTER TABLE 中设置精度和比例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23903392/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:27:55  来源:igfitidea点击:

How to set precision and scale in ALTER TABLE

postgresqltypesprecisionddlarbitrary-precision

提问by Akash Kumar

I have working code with PostgreSQL 9.3:

我有 PostgreSQL 9.3 的工作代码:

ALTER TABLE meter_data ALTER COLUMN w3pht TYPE float USING (w3pht::float);

but don't know how to set precisionand scale.

但不知道如何设置precisionscale

回答by Erwin Brandstetter

The type floatdoes not have precision and scale. Use numeric(precision, scale)instead if you need that.

该类型float没有精度和比例。numeric(precision, scale)如果需要,请改用。

Per documentation:

根据文档:

The data types realand double precisionare inexact, variable-precision numeric types.

数据类型realdouble precision是不精确的、精度可变的数字类型。

For your given example:

对于您给定的示例:

ALTER TABLE meter_data ALTER COLUMN w3pht TYPE numeric(15,2)
USING w3pht::numeric(15,2)  -- may or may not be required

The manual:

手册:

A USINGclause must be provided if there is no implicit or assignment cast from old to new type.

一个USING如果从旧到新类型没有隐含或者赋值转换必须提供条款。

Example: if the old data type is text, you need the USINGclause. If it's float, you don't.

示例:如果旧数据类型是text,则需要该USING子句。如果是float,你没有。

回答by Antti Haapala

As per PostgreSQL documentation, you canselect the minimum number for the floating point numbers using syntax float(n)where nis the minimum number of binarydigits, up to 53.

根据PostgreSQL 文档,您可以使用语法选择浮点数的最小数量,float(n)其中n二进制数字的最小数量,最多 53。

However, to store decimal values at all, use numeric(precision, scale)or its synonym decimal(precision, scale)but notice that these are hard limits; according to the documentation:

但是,要完全存储十进制值,请使用numeric(precision, scale)或其同义词,decimal(precision, scale)但请注意这些是硬限制;根据文档:

If the scale of a value to be stored is greater than the declared scale of the column, the system will round the value to the specified number of fractional digits. Then, if the number of digits to the left of the decimal point exceeds the declared precision minus the declared scale, an error is raised.

如果要存储的值的小数位数大于列的声明小数位数,系统会将值四舍五入到指定的小数位数。然后,如果小数点左边的位数超过声明的精度减去声明的比例,则会引发错误。

Thus your alter table could be:

因此,您的更改表可能是:

ALTER TABLE meter_data
    ALTER COLUMN w3pht TYPE numeric(10, 2)
    USING (w3pht::numeric(10, 2));

for 2 digits right of decimal point and 10 total digits. However if you do not need to specify limits, simple numericwill allow "up to 131072 digits before the decimal point; up to 16383 digits after".

为小数点右边的 2 位数字和 10 位总数字。但是,如果您不需要指定限制,simplenumeric将允许“小数点前最多 131072 位;小数点后最多 16383 位”