【问题标题】:In Postgres, how do you insert possible values for a particular column?在 Postgres 中,如何为特定列插入可能的值?
【发布时间】:2023-01-10 02:32:26
【问题描述】:

我有一个表名ar对于其中的列操作,我只能允许特定值('C'、'R'、'RE'、'M'、'P')。我为它添加了一个检查约束。

要求: 我需要在表中插入 100 万条记录,但操作列有一个约束,即只允许特定值。我正在使用 generate_series() 来生成生成随机值并抛出错误的值。如何避免错误并在列命名操作中插入仅包含所需值('C'、'R'、'RE'、'M'、'P')的 100 万条记录。

CREATE TABLE ar (
  mappingId TEXT,
  actionRequestId integer,
  operation text,
  CONSTRAINT chk_operation CHECK (operation IN ('C', 'R', 'RE', 'M', 'P'))
);
INSERT INTO ar (mappingId, actionRequestId, operation)
SELECT substr(md5(random()::text), 1, 10),
       (random() * 70 + 10)::integer,
       substr(md5(random()::text), 1, 10)
FROM generate_series(1, 1000000);
ERROR: new row for relation "ar" violates check constraint "chk_operation"

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:
    INSERT INTO ar (mappingId, actionRequestId, operation)
     SELECT substr(md5(random()::text), 1, 10),
       (random() * 70 + 10)::integer,
      'C'
    FROM generate_series(1, 200000)
     UNION ALL
    SELECT substr(md5(random()::text), 1, 10),
       (random() * 70 + 10)::integer,
      'R'
    FROM generate_series(1, 200000)
     UNION ALL
    SELECT substr(md5(random()::text), 1, 10),
       (random() * 70 + 10)::integer,
      'RE'
    FROM generate_series(1, 200000)
    

    【讨论】:

      【解决方案2】:

      您可以使用允许的值进行交叉连接:

      INSERT INTO ar (mappingid, actionrequestid, operation)
      SELECT substr(md5(random()::text), 1, 10),
             (random() * 70 + 10)::integer, 
             o.operation
      FROM generate_series(1, 1000000 / 5)
         cross join ( 
           values ('C'), ('R'), ('RE'), ('M'), ('P')
         ) as o(operation);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-07
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 2021-02-11
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        相关资源
        最近更新 更多