繁体   English   中英

在sql中插入重复值

[英]Insert repetitive values in sql

当您有很多重复值时,现在有没有人可以更轻松地在表中插入值。

我有 3 个表,为了简单起见,我用它做了一个动物园的例子。 一张表列出了动物,一个是美国的动物园,一张是您可以在每个动物园中找到的动物。

表:动物

   Id   Animal
   ---------------
   1.   Elephant
   2.   Lion
   3.   Tiger
   4.   Crocodile 
   5.   Bison
   .    .... 
   .    ....

表:动物园

   Id   Zoo
   ---------------
   1.   Alaska Zoo 
   2.   Little Rock Zoo
   3.   Big Bear Alpine Zoo 
   4.   Los Angeles Zoo
   5.   Oakland Zoo
   .    .... 
   .    ....

表:AnimalInZoo

   Zooid    Animalid
   -------------------
   1          1
   1          2
   1          3
   1          4 
   1          5
   2          1
   2          2
   2          3
   2          4 
   2          5

要将值插入 AnimalinZoo 表,我现在写:

INSERT INTO AnimalinZoo (zooid, animals)
VALUES (1, 1), (1, 2), (1, 3), (1, 4), (1, 5);

INSERT INTO AnimalinZoo (zooid, animals)
VALUES (2, 1),  (2, 2), (2, 3), (2, 4), (2, 5);

因为我想在很多动物园中插入这个类似的动物列表,有没有更简单的方法在 sql 中编写它,这样我就不必重复这么多了。 或者我可以使用 SQL 将动物和动物园表中的值直接插入到 AnimalinZoo 中吗?

如果您想要所有动物园中的所有动物,为什么不使用cross join

insert into animal_in_zoo (zooid, animalid)
    select z.id, a.id
    from zoos z cross join
         animals a;

为动物园和动物生成一个数组,然后取消嵌套并交叉连接结果:

with animal_list as
     (select unnest(array[1,4,6,8]) animal)
   , zoo_list as 
     (select unnest(array[3,4,5]) zoo )
insert into animalInZoo (zoo_id, animal_id) 
       select zoo, animal
         from zoo_list cross join animal_list;

或者更好(恕我直言)将过程封装在一个将数组作为参数的 sql 函数中。

create or replace function populate_zoo( zoos integer[], animals integer[] )
returns void 
language sql strict
as $$
    with animal_list as
         (select unnest(animals) animal)
       , zoo_list as 
         (select unnest(zoos) zoo )
    insert into animalInZoo (zoo_id, animal_id) 
        select zoo, animal
          from zoo_list cross join animal_list;
$$;

-- test 
do $$
begin
   perform populate_zoo(zoos    => '{3,4,5}'
                       ,animals => '{1,4,6,8}'
                       );
end; 
$$; 

上面的代码集都产生了相同的结果;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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