【问题标题】:Using WITH clause with INSERT statement in POSTGRESQL在 POSTGRESQL 中使用 WITH 子句和 INSERT 语句
【发布时间】:2018-10-26 03:43:38
【问题描述】:

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

例子:

如果 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 子句的一些查询,但任何其他答案也将不胜感激。

【问题讨论】:

    标签: postgresql with-statement insert-into


    【解决方案1】:

    如果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
    

    【讨论】:

    猜你喜欢
    • 2013-03-12
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2023-01-11
    • 2018-08-23
    相关资源
    最近更新 更多