在POSTGRESQL中使用WITH子句与INSERT语句。

24

我有一个需求,需要从另一张表中获取一列数据,并将该列数据与其他数据插入到另一个表中。

例如:

如果cust_id='11',那么我需要从cust表中获取cust_code(假设它返回cust_code='ABCD'),然后将该cust_code与其他数据一起插入到table_1中,如下所示:

WITH get_cust_code_for_cust_id AS (
    SELECT cust_code FROM cust WHERE cust_id=11
)

INSERT INTO public.table_1(
    cust_code, issue, status, created_on)
    VALUES (SELECT cust_code FROM get_cust_code_for_cust_id, 'New Issue', 'Open', current_timestamp)

但是因为我们还没有调用get_cust_code_for_cust_id查询,所以这个查询不起作用。

我的首选是一些带有WITH子句的查询语句,但是任何其他答案也会被赞赏。

1个回答

48

如果insert语句的源是一个select,则不要使用VALUES关键字。

WITH get_cust_code_for_cust_id AS (
    SELECT cust_code 
    FROM cust 
    WHERE cust_id=11
)
INSERT INTO public.table_1 (cust_code, issue, status, created_on)
SELECT cust_code, 'New Issue', 'Open', current_timestamp 
FROM get_cust_code_for_cust_id;

不过,针对这个问题,你实际上并不需要使用 CTE:

INSERT INTO public.table_1 (cust_code, issue, status, created_on)
SELECT cust_code, 'New Issue', 'Open', current_timestamp  
FROM cust 
WHERE cust_id=11

我想在文档中添加一个链接,特别是提示底部的示例:https://www.postgresql.org/docs/current/static/sql-insert.html - moooeeeep
1
这两个查询对我的情况都完美运行。 - Neeraj Wadhwa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接