#navi(../)
* SELECTした内容をINSERTする [#w4309bce]
SELECT文で取得したレコード群を他のテーブルにINSERTするサンプルを以下に記します。

#contents
#htmlinsertpcsp(db-top.html,db-sp.html)

* 動作確認環境 [#bbc50d34]
-OS

 $ lsb_release -d
 Description:    Ubuntu 12.04.4 LTS

-データベース

 # select version();
                                                version
 ------------------------------------------------------------------------------------------------------
  PostgreSQL 9.1.12 on i686-pc-linux-gnu, compiled by gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3, 32-bit

 mysql> select version();
 +-------------------------+
 | version()               |
 +-------------------------+
 | 5.5.35-0ubuntu0.12.04.2 |
 +-------------------------+

* SELECT内容を太テーブルにINSERTする環境および構文 [#a51615e9]
以下のように2つのテーブルを用意しました。
-SELECTするテーブル
 CREATE TABLE sel (c1 INT, c2 INT, c3 BOOLEAN);
-SELECTした内容をINSERTするテーブル
 CREATE TABLE ins (a INT, b INT);

以下の内容をselテーブルにINSERTしました。
 INSERT INTO sel VALUES(1,1,False);
 INSERT INTO sel VALUES(2,2,True);
 INSERT INTO sel VALUES(3,3,False);
 INSERT INTO sel VALUES(4,4,True);
 INSERT INTO sel VALUES(5,5,False);
 INSERT INTO sel VALUES(6,6,True);

以下のSQL構文でselテーブルのc3カラムがTrueの情報がinsテーブルにINSERTされます。
 INSERT INTO ins SELECT c1,c2 FROM sel WHERE c3 = True;

実際に実行した時の操作出力です。
 postgres@ubuntu:~$ createdb db1
 postgres@ubuntu:~$ psql db1
 psql (9.1.12)
 Type "help" for help.
 
 db1=#  CREATE TABLE sel (c1 INT, c2 INT, c3 BOOLEAN);
 CREATE TABLE
 db1=#  CREATE TABLE ins (a INT, b INT);
 CREATE TABLE
 db1=#  INSERT INTO sel VALUES(1,1,False);
  INSERT INTO sel VALUES(3,3,False);
  INSERT INTO sel VALUES(4,4,True);
  INSERT INTO sel VALUES(5,5,False);
 INSERT 0 1
 db1=#  INSERT INTO sel VALUES(2,2,True);
 INSERT 0 1
 db1=#  INSERT INTO sel VALUES(3,3,False);
 INSERT 0 1
 db1=#  INSERT INTO sel VALUES(4,4,True);
 INSERT 0 1
 db1=#  INSERT INTO sel VALUES(5,5,False);
 INSERT 0 1
 db1=#  INSERT INTO sel VALUES(6,6,True);
 INSERT 0 1
 db1=# select * from sel;
  c1 | c2 | c3
 ----+----+----
   1 |  1 | f
   2 |  2 | t
   3 |  3 | f
   4 |  4 | t
   5 |  5 | f
   6 |  6 | t
 (6 rows)
 
 db1=# select * from ins;
  a | b
 ---+---
 (0 rows)
 
 db1=#  INSERT INTO ins SELECT c1,c2 FROM sel WHERE c3 = True;
 INSERT 0 3
 db1=# select * from ins;
  a | b
 ---+---
  2 | 2
  4 | 4
  6 | 6
 (3 rows)

以上、SELECTした内容をINSERTするINSERT...SELECTのサンプルでした。

#htmlinsertpcsp(db-btm.html,db-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS