11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PostgreSQL TEMPORARY TABLEの実用例 (Glue SQL)

Last updated at Posted at 2014-11-18

PostgreSQL TEMPORARY TABLEの実用例 (Glue SQL)

TableAとTableBでそれぞれデータが入っており、
TableA id=1 と TableB id=4
TableA id=2 と TableB id=5
TableA id=3 と TableB id=6
        ・
        ・
        ・
のデータをそれぞれ結合して集計したい

みたいなわがまま仕様に対応する時のSQL

イメージとしては

TableA   <JOIN> tempテーブル <JOIN> TableB

みたいな感じ

-- テンポラリテーブルを作成
-- 対応表としてのデータを入れる
CREATE TEMPORARY TABLE hoge As SELECT 
	*
FROM  
	(VALUES
		(1, 4), 
		(2, 5),
		(3, 6)
	) AS t (id, cid);


-- 同一トランザクション内なら、テンポラリテーブルにインサートも可能
INSERT INTO hoge values (100,200);


-- TMPテーブルを後付のHBTMテーブルみたいに使えます
SELECT
	*
FROM
	-- テーブルA
	tableA
LEFT OUTER JOIN 
	-- Temporaryテーブル
	hoge 
ON (hoge.id = users.id)
LEFT OUTER JOIN 
	-- テーブルB
	tableB
ON (hoge.id = tableB.id)
ORDER BY
 	hoge.id;
11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?