假设我将表 customer2 定义为:
CREATE TABLE customer2(
customer_id bigint NOT NULL DEFAULT nextval(('customer.customer_identity'::text)::regclass),
customer_name character varying
CONSTRAINT customer2_pkey PRIMARY KEY (customer_id)
)
我有另一个名为 customer1 的表,具有相同的表定义。在插入 customer2 之前,我想检查 customer1 以查看是否存在相同 customer_name 的 customer_id,如果存在则使用它。我的插入语句与此类似:
INSERT INTO customer2(
customer_id,
customer_name)
SELECT customer_id, --null if not found in customer1 table
nc.customer_name
FROM new_customers nc
LEFT OUTER JOIN customer1 c1 on c1.customer_name = nc.customer_name
运行此插入时,出现错误““customer_id”列中的空值违反了非空约束”。当我没有要插入的 customer_id 时,有没有办法使用默认序列?显然,我可以编写两个不同的插入语句,但很遗憾,这是很重要且看似不必要的代码重复,这让我的编程天性感到厌烦。
最佳答案
您不能只使用 coalesce
和 nextval
来仅在序列为 null 时使用它。
INSERT INTO customer2(
coalesce(customer_id, nextval('customer.customer_identity')),
customer_name)
SELECT customer_id, --null if not found in customer1 table
nc.customer_name
FROM new_customers nc
LEFT OUTER JOIN customer1 c1 on c1.customer_name = nc.customer_name
关于postgresql - 有条件地覆盖单个插入中的默认 PK 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33220613/