Skip to content

Instantly share code, notes, and snippets.

@k-yamao
Created February 1, 2017 10:24
Show Gist options
  • Save k-yamao/5eaf7a2ca4c973be534da6f91bda0508 to your computer and use it in GitHub Desktop.
Save k-yamao/5eaf7a2ca4c973be534da6f91bda0508 to your computer and use it in GitHub Desktop.
内部結合してSELECTした結果をINSERTする 特定のカラムは固定値
--サンプルテーブル
--table1
CREATE TABLE table1 (
id serial NOT NULL,
  name text,
  text text
);
--table2
CREATE TABLE table2 (
  id serial NOT NULL,
  text text
);
--table3
CREATE TABLE table3 (
  id serial NOT NULL,
  text text,
  hoge text
);
--table2とtable3を内部結合してtable1へインサート
INSERT INTO table1 (name, text)
SELECT
'hoge' AS name, --特定のカラム
table3.text AS text
FROM
table2
INNER JOIN table3 ON table2.id = table3.id
--table2のid=1をtable1へインサート
INSERT INTO table1 (name, text)
SELECT
'hoge' AS name, --特定のカラム
table2.text AS text
FROM
table2
WHERE
id = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment