Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在POSTGRESQL中使用WITH子句和INSERT语句_Postgresql_With Statement_Insert Into - Fatal编程技术网

在POSTGRESQL中使用WITH子句和INSERT语句

在POSTGRESQL中使用WITH子句和INSERT语句,postgresql,with-statement,insert-into,Postgresql,With Statement,Insert Into,我有一个需求,我需要从另一个表中获取一列,并将该列数据与其他数据一起插入到另一个表中 例如: 如果cust_id='11',那么我需要从cust表中获取cust_代码(假设它返回cust_代码='ABCD'),然后将该cust_代码与其他一些数据一起插入表_1,如下所示: WITH get_cust_code_for_cust_id AS ( SELECT cust_code FROM cust WHERE cust_id=11 ) INSERT INTO public.table_1

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

例如:

如果cust_id='11',那么我需要从cust表中获取cust_代码(假设它返回cust_代码='ABCD'),然后将该cust_代码与其他一些数据一起插入表_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)
但是这个查询不起作用,因为我们没有为客户id调用
get\u cust\u code\u查询


我的首选是一些带有
子句的查询,但任何其他答案也将不胜感激

如果
insert
语句的源是
select
donot则使用
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

我想添加一个到文档的链接,特别是底部示例的提示:这两个查询都非常适合我的场景。