Programing

postgresql : INSERT INTO… (SELECT *…)

crosscheck 2020. 8. 10. 07:39
반응형

postgresql : INSERT INTO… (SELECT *…)


표준 SQL인지 확실하지 않습니다.

 INSERT INTO tblA 
 (SELECT id, time 
    FROM tblB 
   WHERE time > 1000)  

내가 찾고있는 것은 : tblA와 tblB가 다른 DB 서버에 있다면 어떻게 될까요 ?

PostgreSql이 유틸리티를 제공하거나 사용에 도움이되는 기능이 있습니까? INSERT query with PGresult struct

내 말은 SELECT id, time FROM tblB ...를 반환합니다 PGresult*사용하여 PQexec. PQexecINSERT 명령을 실행하기 위해 다른 구조체에서이 구조체를 사용할 수 있습니까?

편집 :
가능하지 않으면 PQresult *에서 값을 추출하고 다음과 같은 여러 INSERT 문 구문을 만듭니다.

INSERT INTO films (code, title, did, date_prod, kind) VALUES
    ('B6717', 'Tampopo', 110, '1985-02-10', 'Comedy'),
    ('HG120', 'The Dinner Game', 140, DEFAULT, 'Comedy'); 

이것으로 준비된 성명서를 작성할 수 있습니까! :(


Henrik이 작성한 것처럼 dblink를 사용하여 원격 데이터베이스에 연결하고 결과를 가져올 수 있습니다. 예를 들면 :

psql dbtest
CREATE TABLE tblB (id serial, time integer);
INSERT INTO tblB (time) VALUES (5000), (2000);

psql postgres
CREATE TABLE tblA (id serial, time integer);

INSERT INTO tblA
    SELECT id, time 
    FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB')
    AS t(id integer, time integer)
    WHERE time > 1000;

TABLE tblA;
 id | time 
----+------
  1 | 5000
  2 | 2000
(2 rows)

PostgreSQL에는 레코드 의사 유형 (함수의 인수 또는 결과 유형에만 해당)이있어 다른 (알 수없는) 테이블에서 데이터를 쿼리 할 수 ​​있습니다.

편집하다:

원하는 경우 준비된 진술로 만들 수 있으며 잘 작동합니다.

PREPARE migrate_data (integer) AS
INSERT INTO tblA
    SELECT id, time
    FROM dblink('dbname=dbtest', 'SELECT id, time FROM tblB')
    AS t(id integer, time integer)
    WHERE time > $1;

EXECUTE migrate_data(1000);
-- DEALLOCATE migrate_data;

편집 (예, 다른) :

방금 수정 된 질문을 봤습니다 (중복으로 마감되었거나 이와 매우 유사 함).

내 이해가 정확하다면 (postgres에는 tbla가 있고 dbtest에는 tblb가 있으며 위와 같이 로컬 삽입 으로 원격 선택이 아닌 로컬 선택으로 원격 삽입 을 원합니다 ) :

psql dbtest

SELECT dblink_exec
(
    'dbname=postgres',
    'INSERT INTO tbla
        SELECT id, time
        FROM dblink
        (
            ''dbname=dbtest'',
            ''SELECT id, time FROM tblb''
        )
        AS t(id integer, time integer)
        WHERE time > 1000;'
);

중첩 된 dblink가 마음에 들지 않지만 AFAIK dblink_exec 본문 에서 tblB를 참조 할 수 없습니다 . LIMIT를 사용하여 상위 20 개 행을 지정하지만 먼저 ORDER BY 절을 사용하여 정렬해야한다고 생각합니다.


If you want insert into specify column:

INSERT INTO table (time)
(SELECT time FROM 
    dblink('dbname=dbtest', 'SELECT time FROM tblB') AS t(time integer) 
    WHERE time > 1000
);

You can use dblink to create a view that is resolved in another database. This database may be on another server.


This notation (first seen here) looks useful too:

insert into postagem (
  resumopostagem,
  textopostagem,
  dtliberacaopostagem,
  idmediaimgpostagem,
  idcatolico,
  idminisermao,
  idtipopostagem
) select
  resumominisermao,
  textominisermao,
  diaminisermao,
  idmediaimgminisermao,
  idcatolico ,
  idminisermao,
  1
from
  minisermao    

Here's an alternate solution, without using dblink.

Suppose B represents the source database and A represents the target database: Then,

  1. Copy table from source DB to target DB:

    pg_dump -t <source_table> <source_db> | psql <target_db>
    
  2. Open psql prompt, connect to target_db, and use a simple insert:

    psql
    # \c <target_db>;
    # INSERT INTO <target_table>(id, x, y) SELECT id, x, y FROM <source_table>;
    
  3. At the end, delete the copy of source_table that you created in target_table.

    # DROP TABLE <source_table>;
    

insert into TABLENAMEA (A,B,C,D) 
select A::integer,B,C,D from TABLENAMEB

참고URL : https://stackoverflow.com/questions/6083132/postgresql-insert-into-select

반응형