我有一个要求,我需要从另一个表中获取一列,并将该列数据与其他一些数据一起插入到另一个表中。
例:
如果 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