#author("2020-07-05T12:00:48+09:00","default:ryuichi","ryuichi")
#author("2020-07-05T12:03:12+09:00","default:ryuichi","ryuichi")
* CTEでINSERTされた行のデータを別のINSERTに使う [#i5b52873]
** 前提 [#uddfed02]
CREATE TABLE category ( category_id serial primary key, category_name text );
CREATE TABLE item ( item_id serial primary key, item_name text, category_id int );
- categoryテーブルにレコードを挿入後、そのレコードのプライマリーキーのcategory_idを使って別のテーブルであるitemテーブルにレコードを挿入する
** CTEを使う場合 [#la2034b7]
WITH category_cte AS (
INSERT INTO category ( category_name ) VALUES ( 'cat_a' )
RETURNING category_id
)
INSERT INTO item ( item_name, category_id )
SELECT 'item_a', category_id FROM category_cte;
- categoryテーブルにINSERTするCommon Table Expression(CTE)を作り、その中でRETURNINGでcategory_idを返す
- itemテーブルのINSERTにはCTEが返すデータを使う
** シーケンスを参照する場合 [#caecf824]
*** lastval() [#e1fbc2a1]
INSERT INTO category ( category_name ) VALUES ( 'cat_b' );
INSERT INTO item ( item_name, category_id ) VALUES ( 'item_b', lastval() );
*** currval() [#f1bd0983]
INSERT INTO category ( category_name ) VALUES ( 'cat_c' );
INSERT INTO item ( item_name, category_id ) VALUES ( 'item_c',
currval(pg_get_serial_sequence('category', 'category_id')) );
** 参考 [#r22cfe59]
- https://www.postgresql.jp/document/9.6/html/dml-returning.html
- https://rob.conery.io/2015/02/08/inserting-using-new-record-postgres/