PostgreSQL: insert from another table

后端 未结 4 896
悲&欢浪女
悲&欢浪女 2021-01-30 00:39

I\'m trying to insert data to a table from another table and the tables have only one column in common. The problem is, that the TABLE1 has columns that won\'t accept null value

相关标签:
4条回答
  • 2021-01-30 00:57

    For referential integtity :

    insert into  main_tbl (col1, ref1, ref2, createdby)
    values ('col1_val',
            (select ref1 from ref1_tbl where lookup_val = 'lookup1'),
            (select ref2 from ref2_tbl where lookup_val = 'lookup2'),
            'init-load'
           );
    
    0 讨论(0)
  • 2021-01-30 01:01

    Very late answer, but I think my answer is more straight forward for specific use cases where users want to simply insert (copy) data from table A into table B:

    INSERT INTO table_b (col1, col2, col3, col4, col5, col6)
    SELECT col1, 'str_val', int_val, col4, col5, col6
    FROM table_a
    
    0 讨论(0)
  • 2021-01-30 01:08

    Just supply literal values in the SELECT:

    INSERT INTO TABLE1 (id, col_1, col_2, col_3)
    SELECT id, 'data1', 'data2', 'data3'
    FROM TABLE2
    WHERE col_a = 'something';
    

    A select list can contain any value expression:

    But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

    And a string literal is certainly a value expression.

    0 讨论(0)
  • 2021-01-30 01:12

    You could use coalesce:

    insert into destination select coalesce(field1,'somedata'),... from source;
    
    0 讨论(0)
提交回复
热议问题