【问题标题】:How to count number of digits in Postgres integer data type?如何计算 Postgres 整数数据类型的位数?
【发布时间】:2015-08-12 07:50:53
【问题描述】:

我需要在 postgres 中将“整数”类型字段中的位数限制为 6 或 7。

基本上它应该接受 123456 或 1234567,但它不应该接受 12345 或 12345678。 我怎样才能做到这一点??

【问题讨论】:

  • 检查 100000 到 9999999 之间的 abs(value)?

标签: sql database postgresql postgresql-9.2


【解决方案1】:

您可以使用floor(log(i)+1 获取数字中的位数(即base10 日志)。

DB> CREATE TEMP TABLE t (
      i integer CONSTRAINT i_has_6_or_7_digits CHECK (floor(log(abs(i))+1) BETWEEN 6 AND 7)
    );
CREATE TABLE
Time: 5,676 ms

DB> INSERT INTO t VALUES (123456), (1234567);
INSERT 0 2
Time: 0,471 ms

DB> INSERT INTO t VALUES (12345);
ERROR:  23514: new row for relation "t" violates check constraint "i_has_6_or_7_digits"
DETAIL:  Failing row contains (12345).
SCHEMA NAME:  pg_temp_2
TABLE NAME:  t
CONSTRAINT NAME:  i_has_6_or_7_digits
LOCATION:  ExecConstraints, execMain.c:1661
Time: 0,468 ms

DB> INSERT INTO t VALUES (12345678);
ERROR:  23514: new row for relation "t" violates check constraint "i_has_6_or_7_digits"
DETAIL:  Failing row contains (12345678).
SCHEMA NAME:  pg_temp_2
TABLE NAME:  t
CONSTRAINT NAME:  i_has_6_or_7_digits
LOCATION:  ExecConstraints, execMain.c:1661
Time: 0,215 ms

【讨论】:

  • 感谢 Madhivanan 和 Marth!这两种解决方案都很好,但哪一种更快?
【解决方案2】:

有一个检查约束

check (value>99999 and value<=9999999)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2021-11-10
    • 2015-03-09
    • 2023-04-08
    相关资源
    最近更新 更多