简体   繁体   中英

Add multiple entries for sequential items postgresql

I want to add multiple entries, with 1 column staying the same, and 1 column increasing by 1 every time. To do this manually I would have to do

INSERT INTO table (column1, column2) VALUES ('1'::integer, '1'::integer)returning column1, column2;
INSERT INTO table (column1, column2) VALUES ('1'::integer, '2'::integer)returning column1, column2;
INSERT INTO table (column1, column2) VALUES ('1'::integer, '3'::integer)returning column1, column2;

etc

Is there a way I could do the numbers 1 to 34000 in 1 query?

Use generate_series() :

INSERT INTO table (column1, column2) 
    SELECT 1, gs.n
    FROM generate_series(1, 34000) gs(n);

Note: There is no need to convert a string to an integer. In general, a number literal is fine. In any case, Postgres would convert the number literal to the correct type if needed (say int or numeric or float or whatever).

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