逻辑:我想在loyalty_customers
为空且customers.user_id
更新为customers.user_id
loyalty_customers.id
我有一个查询,但它不起作用:
UPDATE customers
SET user_id = (
INSERT INTO loyalty_users (name) VALUES ('anonymous')) RETURNING id
)
WHERE user_id IS NULL;
错误如:
LINE 3: INSERT INTO loyalty_users
看起来INSERT无法被任何查询包装,我尝试了这个查询,它仍然无法正常工作:
SELECT id FROM (
INSERT INTO loyalty_users (name) VALUES ('anonymous')) RETURNING id);
但是,独立的INSERT查询就像魅力一样:
INSERT INTO loyalty_users (name) VALUES ('anonymous')) RETURNING id;
答案 0 :(得分:0)
做这件事可能是正确的方法:
WITH updated_customer AS (
UPDATE customers
SET name = 'anonymous'
WHERE user_id IS NULL
RETURNING user_id AS id
)
INSERT INTO loyalty_users SELECT * FROM updated_customer;
这对我有用,但如果您有其他想法,请在此问题中发表评论。