postgresql 在Postgres中,如何为特定列插入可能的值?

6tqwzwtp  于 2023-01-13  发布在  PostgreSQL
关注(0)|答案(2)|浏览(170)

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

要求:我需要在表中插入100万条记录,但operation列具有仅允许特定值的约束。我正在使用generate_series()生成值,该值会生成随机值并引发错误。如何避免错误并在名为operation的列中插入仅包含必需值('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"
7y4bm7vi

7y4bm7vi1#

您可以使用允许的值执行交叉联接:

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);
8yparm6h

8yparm6h2#

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)

相关问题