【问题标题】:Insert multiple rows with one column from another table插入多行,其中一列来自另一个表
【发布时间】:2016-01-19 11:23:38
【问题描述】:

我有两张桌子

 CREATE TABLE table1 (
    id bigint NOT NULL,
    name character varying(255),
    CONSTRAINT table1_pkey PRIMARY KEY (id)
 );

 CREATE TABLE table2 (   
     id bigint NOT NULL,
     name character varying(255),
     table1_id bigint,
     CONSTRAINT table2_pkey PRIMARY KEY (id), 
     CONSTRAINT fk_table1_table2 FOREIGN KEY (table1_id) 
     REFERENCES table1 (id) MATCH SIMPLE
 );

现在我要做的是为 table1 中的每个条目添加 table2 中的条目

即如果我的表 1 有条目

|id | name   |
|1  | First  | 
|2  | Second | 
|3  | Third  | 

我需要在table2中创建三个条目

insert into table2 (id,name,table2_id) values (nextval('table2_seq'),'new entry', 1);
insert into table2 (id,name,table2_id) values (nextval('table2_seq'),'new entry', 2);
insert into table2 (id,name,table2_id) values (nextval('table2_seq'),'new entry', 3);

并且由于每个新条目仅更改外键,我想知道是否有可能使此过程自动化。 是否可以通过查询来实现,还是我应该看程序?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    使用基于选择的插入:

    insert into table2 (id,name,table1_id)
    select nextval('table2_seq'), 'new entry', t1.id
    from table1;
    

    【讨论】:

      【解决方案2】:

      我努力在子查询中获得“SELECT ... WHERE”,可能没有足够的咖啡,但最终确定了以下语法:

      insert into table (col1, col2 ...)
      select 'staticval1',
      r.variable1 from reftable r where r.variable2 = 'Some search term'
      ...;
      

      【讨论】:

        猜你喜欢
        • 2018-09-27
        • 2016-05-18
        • 2014-09-09
        • 1970-01-01
        • 2021-02-03
        • 2020-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多