[英]Using WITH clause with INSERT statement in POSTGRESQL
我有一個要求,我需要從另一個表中獲取一列,並將該列數據與其他一些數據插入到另一個表中。
例:
如果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
子句的查詢,但任何其他答案也將受到贊賞。
如果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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.