简体   繁体   中英

INSERT with VALUES and subquery, postgres

I need to insert several rows at once, and values for some columns should be taken from 'VALUES', and for some columns, I would need to use a subquery. Assuming that subquery will return exactly the same amount of rows as I'm trying to insert. Something like this:

WITH subq AS (
   --returns 3 rows
   SELECT param FROM tbl2 WHERE status = 1  
)
INSERT INTO tbl1 (col1, col2, col3)
VALUES
('col1_val1', 'col2_val1', subq.row1.param),
('col1_val2', 'col2_val2', subq.row2.param),
('col1_val3', 'col2_val3', subq.row3.param)

You can add the text to the CTE and make a INSERT INTO SELECT

WITH CTE as 
(
(SELECT 'col1_val1', 'col2_val1', param FROM tbl2 WHERE status = 1 ORDER By params LIMIT 1 OFFSET 0)
UNION ALL
(SELECT 'col1_val2', 'col2_val2', param FROM tbl2 WHERE status = 1 ORDER By params LIMIT 1 OFFSET 1)
UNION ALL
(SELECT 'col1_val3', 'col2_val3', param FROM tbl2 WHERE status = 1 ORDER By params LIMIT 1 OFFSET 2))
INSERT INTO tbl1 (col1, col2, col3)
SELECT * FROM CTE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM