在PostgreSQL的一栏中添加数字范围(1..5)

时间:2018-11-22 20:47:13

标签: sql postgresql

我要在列中插入数字1到5

INSERT INTO public.npc(name, gold, info, id, quest_level)
VALUES ('test',200,'do_that',1,(1..5)

2 个答案:

答案 0 :(得分:0)

我假设您的quest_level的数据类型为int[]

 CREATE TABLE public.npc(
    name text, 
    gold int, 
    info text, 
    id int, 
    quest_level int[]
);

在这种情况下,您可以这样插入值:

INSERT INTO public.npc (name, gold, info, id, quest_level) VALUES 
('test',200,'do_that',1, (SELECT array_agg(g.i) 
                          FROM generate_series(1,5) as g(i)));

如果quest_level具有另一种数据类型,例如text,则必须进行强制转换:

 CREATE TABLE public.npc(
    name text, 
    gold int, 
    info text, 
    id int, 
    quest_level text
 );

INSERT INTO public.npc (name, gold, info, id, quest_level) VALUES 
('test',200,'do_that',1, (SELECT array_agg(g.i) :: text
                          FROM generate_series(1,5) as g(i)));

答案 1 :(得分:0)

如果要引入 5 行,则:

INSERT INTO public.npc(name, gold, info, id, quest_level)
    SELECT 'test', 200, 'do_that', 1, gs.n
    FROM generate_series(1, 5) gs(n);