<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Postgresql &#8211; REONTOSANTA</title>
	<atom:link href="https://knowledge.reontosanta.com/archives/category/database/postgresql/feed" rel="self" type="application/rss+xml" />
	<link>https://knowledge.reontosanta.com</link>
	<description>Collection of personal knowledge</description>
	<lastBuildDate>Tue, 24 Jul 2018 05:37:57 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<atom:link rel='hub' href='https://knowledge.reontosanta.com/?pushpress=hub'/>
<site xmlns="com-wordpress:feed-additions:1">83369280</site>	<item>
		<title>Postgresqlで重複レコードを削除する</title>
		<link>https://knowledge.reontosanta.com/archives/594</link>
					<comments>https://knowledge.reontosanta.com/archives/594#comments</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Wed, 15 Jul 2015 07:22:38 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://knowledge.reontosanta.com/?p=594</guid>

					<description><![CDATA[DISTINCT句によって検索結果がユニークになることを利用し、結果&#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>DISTINCT句によって検索結果がユニークになることを利用し、結果を別テーブルにコピーして戻す。</p>
<p>※制約(プライマリキー制約、 非NULL制約など)やデフォルト値などの設定は、自動的にコピーされないので適宜再設定する。</p><pre class="urvanov-syntax-highlighter-plain-tag">--重複レコード除去（一時テーブル）
CREATE TABLE tmp_table AS SELECT DISTINCT * FROM target_table;
--元テーブルバックアップ
CREATE TABLE bk_table AS SELECT * FROM target_table;
--元テーブル削除
DROP TABLE target_table;
--一時テーブルを元テーブルの名称にリネーム
ALTER TABLE tmp_table RENAME TO target_table;</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-1716904251"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-2304874995"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/594/feed</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">594</post-id>	</item>
		<item>
		<title>PostgresqlでSQL文中に改行コードを挿入する</title>
		<link>https://knowledge.reontosanta.com/archives/303</link>
					<comments>https://knowledge.reontosanta.com/archives/303#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Mon, 19 Jan 2015 00:56:50 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://knowledge.reontosanta.com/?p=303</guid>

					<description><![CDATA[改行（LF）したい箇所にchr(10)を挿入する。 [crayon-&#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>改行（LF）したい箇所にchr(10)を挿入する。</p><pre class="urvanov-syntax-highlighter-plain-tag">INSERT INTO target_table (target_col) VALUES ('foo' || chr(10) || 'bar');</pre><p>ASCIIコード参考。</p>

<table id="tablepress-17" class="tablepress tablepress-id-17">
<thead>
<tr class="row-1">
	<th class="column-1">ASCIIコード</th><th class="column-2">内容</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">chr(9)</td><td class="column-2">タブ</td>
</tr>
<tr class="row-3">
	<td class="column-1">chr(13)</td><td class="column-2">CR</td>
</tr>
<tr class="row-4">
	<td class="column-1">chr(10)</td><td class="column-2">LF</td>
</tr>
<tr class="row-5">
	<td class="column-1">chr(32)</td><td class="column-2">スペース</td>
</tr>
<tr class="row-6">
	<td class="column-1">chr(39)</td><td class="column-2">引用符(')</td>
</tr>
</tbody>
</table>

<p>&nbsp;</p>
<p>また、文字列の前にE（小文字でもOK）を入力することでも改行コードを挿入できる。</p><pre class="urvanov-syntax-highlighter-plain-tag">INSERT INTO target_table (target_col) VALUES (E'foo\nbar');</pre><p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-2445693613"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-758828564"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/303/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">303</post-id>	</item>
		<item>
		<title>PostgresqlでコマンドラインからCSV出力</title>
		<link>https://knowledge.reontosanta.com/archives/287</link>
					<comments>https://knowledge.reontosanta.com/archives/287#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Mon, 12 Jan 2015 02:10:05 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://knowledge.reontosanta.com/?p=287</guid>

					<description><![CDATA[COPYコマンドを利用するパターン 単純なCOPYコマンド [cra&#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<h2>COPYコマンドを利用するパターン</h2>
<p>単純なCOPYコマンド</p><pre class="urvanov-syntax-highlighter-plain-tag">COPY tablename TO '/tmp/output.csv' DELIMITER ','</pre><p>列指定のCOPYコマンド</p><pre class="urvanov-syntax-highlighter-plain-tag">COPY tablename(col1, col2, col3) TO '/tmp/output.csv' DELIMITER ','</pre><p>SELECT結果のCOPYコマンド</p><pre class="urvanov-syntax-highlighter-plain-tag">COPY (SELECT * FROM tablename) TO '/tmp/output.csv' DELIMITER ','</pre><p>※オプション<br />
FORMAT：読み取りまたは書き込みに使用するデータ書式を選択（text、csv（カンマ区切り値）、またはbinary、デフォルトはtext）<br />
DELIMITER：フィールド区切り文字の指定（書式でのデフォルトはタブ文字、CSV書式ではカンマ）</p>
<p>出力結果を復元するにはCOPY…FROM</p><pre class="urvanov-syntax-highlighter-plain-tag">COPY tablename FROM '/tmp/output.csv'</pre><p>&nbsp;</p>
<div class="knowl-content" style="margin-top: 40px;" id="knowl-2658523320"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="4196732648" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><h2>psqlコマンドを利用するパターン</h2>
<p>SQLを記述してエクスポート</p><pre class="urvanov-syntax-highlighter-plain-tag">psql -U {user} {dbname} -c 'SELECT * FROM tablename' -A -F, -t &gt; output.csv</pre><p>※オプション<br />
-A：位置揃えなしの出力モードに切り替える（デフォルトの出力モードは位置揃えあり）<br />
-F：位置揃えを行わない出力におけるフィールド区切り文字の指定（後続の文字を区切り文字とする、デフォルトは ASCII の縦棒&#8221;|&#8221;）<br />
-t：列名と結果の行数フッタなどの表示を無効にする</p>
<p>SQLファイルを指定してエクスポート</p><pre class="urvanov-syntax-highlighter-plain-tag">psql -U {user} {dbname} -f export_csv.sql -A -F, &gt; output.csv</pre><p></p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT
    '"' || coalesce(col1, '') || '"'
  , '"' || coalesce(cast(col2 as text), '') || '"'
FROM
    tablename;</pre><p>メタコマンドを利用してエクスポート</p><pre class="urvanov-syntax-highlighter-plain-tag">psql -U {user} {dbname} -f export_csv_meta.sql</pre><p></p><pre class="urvanov-syntax-highlighter-plain-tag">\o output.csv  --出力先を output.csv へ切り替え
\pset format unaligned  --現在有効なフィールド区切り文字で区切って出力
\pset fieldsep ','  --位置揃えなしの出力書式で使用されるフィールド区切り文字を指定
\pset tuples_only  --出力列名ヘッダと行数フッタの表示を切り替え

SELECT
    '"' || coalesce(col1, '') || '"'
  , '"' || coalesce(cast(col2 as text), '') || '"'
FROM
    tablename;

\o  --出力先を元に戻す</pre><p></p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-3690912764"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-3115887166"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/287/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">287</post-id>	</item>
		<item>
		<title>PostgresqlでNVL（NULL置換）</title>
		<link>https://knowledge.reontosanta.com/archives/169</link>
					<comments>https://knowledge.reontosanta.com/archives/169#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Thu, 18 Dec 2014 03:30:52 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://knowledge.reontosanta.com/?p=169</guid>

					<description><![CDATA[Postgresqlでは、OracleやInformix等でNULL&#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>Postgresqlでは、OracleやInformix等でNULL置換を行うNVL関数が存在しない。</p>
<p>代わりにCOALESCE（コアレス）関数が用意されている。</p>
<p>使い方というよりは綴りを忘れてしまうのでメモ。</p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT COALESCE(target_col, " ") FROM target_table;</pre><p>なお、正確にはNVL関数は「該当する値がNULLの場合の代替値を返す」仕様に対して、CALESCEは「NULLでない自身の最初の引数を返す」仕様であり引数を列挙することができる。</p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT COALESCE(target_col1, target_col2, target_col3, " ") FROM target_table;</pre><p>上記の場合は、target_col1がNULLならtarget_col2、それもNULLならtarget_col3。それでもNULLなら&#8221; &#8220;、といった「IF-ELSE構文」のような挙動をする。</p>
<p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-3998467766"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-3674918256"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/169/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">169</post-id>	</item>
		<item>
		<title>Postgresqlで接続先を動的変更できるDBLINKのサンプル</title>
		<link>https://knowledge.reontosanta.com/archives/131</link>
					<comments>https://knowledge.reontosanta.com/archives/131#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Wed, 10 Dec 2014 02:30:26 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://knowledge.reontosanta.com/?p=131</guid>

					<description><![CDATA[DBLINKの基本的な構文例。 [crayon-68487cec4d&#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>DBLINKの基本的な構文例。</p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT *
FROM DBLINK('host=XXX port=5432 dbname=XXX user=XXX password=XXX'
           ,'SELECT col1, col2 FROM target')
           AS T1 (col1 text, col2 text)
ORDER BY T1.col2
;</pre><p>接続先を動的に変更する為、接続先情報をテーブルで管理する。</p><pre class="urvanov-syntax-highlighter-plain-tag">CREATE TABLE linktest
(
    key character varying(1) NOT NULL,
    value character varying(200) NOT NULL,
    CONSTRAINT linktest_pk PRIMARY KEY (key)
)
;</pre><p>接続先情報を取得する為のPL/pgSQLを定義。</p><pre class="urvanov-syntax-highlighter-plain-tag">-- Function: get_dblinkstr(character varying)
-- DROP FUNCTION get_dblinkstr(character varying);
CREATE OR REPLACE FUNCTION get_dblinkstr(argkey character varying)
 RETURNS character varying AS
$BODY$
DECLARE
-- &lt;TITLE&gt;DBLINK接続文字列取得&lt;/TITLE&gt;
-- &lt;REMARKS&gt;
--  keyに一致するDBLINK接続文字列を取得する
-- &lt;/REMARKS&gt;
    fldvalue    linktest.value%TYPE;
BEGIN
    BEGIN
        SELECT value
        INTO   fldvalue
        FROM   linktest
        WHERE  key = argkey;
    EXCEPTION
        WHEN OTHERS THEN
            RETURN NULL;
    END;
    RETURN fldvalue;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
;</pre><p>接続先情報取得関数の利用方法。</p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT * FROM get_dblinkstr('1');</pre><p>接続先情報取得関数を利用したDBLINKを行うVIEWの定義。</p><pre class="urvanov-syntax-highlighter-plain-tag">CREATE VIEW view_test AS
SELECT *
FROM DBLINK(get_dblinkstr('1')
           ,'SELECT col1, col2 FROM target')
           AS T1 (col1 text, col2 text)
;</pre><p>接続先情報取得関数を利用したDBLINKを行うVIEWの参照。</p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT * FROM view_test ORDER BY col1;</pre><p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-1672408467"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-644152550"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/131/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">131</post-id>	</item>
		<item>
		<title>Postgresqlでテーブルの存在確認</title>
		<link>https://knowledge.reontosanta.com/archives/107</link>
					<comments>https://knowledge.reontosanta.com/archives/107#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Mon, 01 Dec 2014 05:22:21 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://knowledge.reontosanta.com/?p=107</guid>

					<description><![CDATA[以下のクエリを実行することでテーブルの存在を確認することができる。 &#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>以下のクエリを実行することでテーブルの存在を確認することができる。</p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT relname FROM pg_class WHERE relkind = 'r' AND relname = 'テーブルID';</pre><p>pg_classには、テーブルや その他の列を保持しているすべての情報が格納されている為、「relkind = ‘r’ 」でテーブルに限定する。</p>
<h3>【relkindの値の意味】</h3>
<ul>
<li>r：通常のテーブル</li>
<li>i：インデックス</li>
<li>S：シーケンス</li>
<li>v：ビュー</li>
<li>c：複合型</li>
<li>s：特別</li>
<li>t：TOAST テーブル</li>
</ul>
<p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-3459913725"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-1391973552"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/107/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">107</post-id>	</item>
		<item>
		<title>Postgresqlで「with recursive」使った再帰クエリ</title>
		<link>https://knowledge.reontosanta.com/archives/45</link>
					<comments>https://knowledge.reontosanta.com/archives/45#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Wed, 26 Nov 2014 05:01:16 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://reontosanta-com.check-netowl.jp/knowledge.reontosanta.com/?p=45</guid>

					<description><![CDATA[PostgreSQL8.4から利用可能な「with recursiv&#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>PostgreSQL8.4から利用可能な「with recursive」使った再帰クエリの利用方法。</p>
<p>会社の下に営業部とシステム開発部があり、それぞれの下に課があるテーブル「department」を用意する。</p>
<p>parent_idには、上位部署のidが格納されている。</p>

<table id="tablepress-1" class="tablepress tablepress-id-1">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">1</td><td class="column-2"></td><td class="column-3">会社</td>
</tr>
<tr class="row-3">
	<td class="column-1">2</td><td class="column-2">1</td><td class="column-3">営業部</td>
</tr>
<tr class="row-4">
	<td class="column-1">3</td><td class="column-2">1</td><td class="column-3">システム開発部</td>
</tr>
<tr class="row-5">
	<td class="column-1">4</td><td class="column-2">2</td><td class="column-3">営業１課</td>
</tr>
<tr class="row-6">
	<td class="column-1">5</td><td class="column-2">2</td><td class="column-3">営業２課</td>
</tr>
<tr class="row-7">
	<td class="column-1">6</td><td class="column-2">3</td><td class="column-3">システム開発１課</td>
</tr>
</tbody>
</table>
<!-- #tablepress-1 from cache -->
<p>このテーブルから、「営業部」とその配下の部署を検索するSQLは以下の通り。</p><pre class="urvanov-syntax-highlighter-plain-tag">with recursive temp(id, parent_id, name) as (
    select id, parent, name
    from dept
    where name = '営業部'
    union all
    select dept.id, dept.parent, dept.name
    from temp, dept
    where dept.parent = temp.id
)
select * from temp;</pre><p>結果。</p>

<table id="tablepress-2" class="tablepress tablepress-id-2">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">2</td><td class="column-2">1</td><td class="column-3">営業部</td>
</tr>
<tr class="row-3">
	<td class="column-1">4</td><td class="column-2">2</td><td class="column-3">営業１課</td>
</tr>
<tr class="row-4">
	<td class="column-1">5</td><td class="column-2">2</td><td class="column-3">営業２課</td>
</tr>
</tbody>
</table>
<!-- #tablepress-2 from cache -->
<p>SQLの解説。（with句とオプションのrecursive修飾子について）</p>
<p>まずは、with句。</p>
<p>with句は、「検索結果に名前を付けて、メモリ上に仮想のテーブルを作る」ための文。</p>
<p>構文は以下の通り。</p><pre class="urvanov-syntax-highlighter-plain-tag">with 仮想テーブル名[ ( カラム名.....) ] as (
    select文1
)
select文2</pre><p>上記の記述では、まずselect文1が実行されて、その検索結果がメモリ上で仮想テーブルになる。</p>
<p>そして、select文2の中で、そのテーブルを検索対象として使用できる。</p>
<p>例えば、「会社の部署の中で、&#8221;営業&#8221;に関係している&#8221;課&#8221;」を検索したい場合。</p>
<p>１．部署名が「課」で終わってる行を検索</p>
<p>２．１．の結果から、さらに部署名が「営業」で始まっている行を検索</p><pre class="urvanov-syntax-highlighter-plain-tag">with temp(id, name) as (
    select id, name 
    from dept
    where name like '%課'
)
select id, name 
from temp
where name like '営業%' ;</pre><p>結果。</p>

<table id="tablepress-3" class="tablepress tablepress-id-3">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">4</td><td class="column-2">2</td><td class="column-3">営業１課</td>
</tr>
<tr class="row-3">
	<td class="column-1">5</td><td class="column-2">2</td><td class="column-3">営業２課</td>
</tr>
</tbody>
</table>
<!-- #tablepress-3 from cache -->
<p>このwith句を前半と後半に分けて考える。</p>
<p>まず、SQLの前半部分。</p><pre class="urvanov-syntax-highlighter-plain-tag">with temp(id, name) as (
    select id, name 
    from dept
    where name like '%課'
)</pre><p>これは、「かっこ内のselect文を実行し、その結果をtempテーブルとする」という意味になる。</p>
<p>このテーブルは実際にはDB上には作られない、SQLが終わると消えてしまう仮想テーブルである。</p>
<p>かっこ内のselect文は「課」で終わってる部門の検索なので、結果は下記のようになる。</p>

<table id="tablepress-4" class="tablepress tablepress-id-4">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">4</td><td class="column-2">2</td><td class="column-3">営業１課</td>
</tr>
<tr class="row-3">
	<td class="column-1">5</td><td class="column-2">2</td><td class="column-3">営業２課</td>
</tr>
<tr class="row-4">
	<td class="column-1">6</td><td class="column-2">3</td><td class="column-3">システム開発１課</td>
</tr>
</tbody>
</table>
<!-- #tablepress-4 from cache -->
<p>次に、with句の後半部分。</p><pre class="urvanov-syntax-highlighter-plain-tag">select id, name 
from temp
where name like '営業%';</pre><p>このselect文では、with句の前半で作られた仮想テーブル「temp」の中で、「営業」で始まっている行を検索している。</p>
<p>結果は以下の通り。</p>

<table id="tablepress-3-no-2" class="tablepress tablepress-id-3">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">4</td><td class="column-2">2</td><td class="column-3">営業１課</td>
</tr>
<tr class="row-3">
	<td class="column-1">5</td><td class="column-2">2</td><td class="column-3">営業２課</td>
</tr>
</tbody>
</table>
<!-- #tablepress-3-no-2 from cache -->
<p>つまり、もう一度前半と後半を一緒に見てみると、</p><pre class="urvanov-syntax-highlighter-plain-tag">with temp(id, name) as (
    select id, name 
    from dept
    where name like '%課'
)
select id,name 
from temp
where name like '営業%';</pre><p>１．まず、部署名が「課」で終わってる行を検索</p>
<p>２．１．の結果から、さらに部署名が「営業」で始まっている行を検索</p>
<p>再帰検索をするには、with句にオプションのrecursive修飾子を付けて、with recursiveとする。</p>
<p>recursive修飾子を付加すると、with句で一時テーブルを作成するselect文で検索する対象テーブルに、その自分自身（つまりその一時テーブル自身）を指定することができる。</p>
<p>例えば、手続き型プログラミングでの再帰呼び出しは、関数が自分自身を呼ぶ。</p>
<p>それと同じように、一時テーブルを作成する時に、その作成途中の自分自身を検索対象にしてしまう。</p>
<p>「with recursive」のSQLを前半、中盤、後半に分けてみてみる。</p>
<p>１．前半</p>
<p>この部分は、再帰の先頭部分を決めるSQLになる。</p><pre class="urvanov-syntax-highlighter-plain-tag">with recursive temp(id, parent_id, name) as(
    select id, parent_id, name 
    from dept
    where name='営業部'</pre><p>1行目は、tempという一時テーブルを作成するSQLの最初の部分。</p>
<p>そのtempの構成内容が記述されているのが2行目以降。</p>
<p>このselect文がまず実行される。</p><pre class="urvanov-syntax-highlighter-plain-tag">select id, parent_id, name 
from dept
where name='営業部'</pre><p>これによって、nameが「営業部」の以下の結果が返る。</p>

<table id="tablepress-5" class="tablepress tablepress-id-5">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">2</td><td class="column-2">1</td><td class="column-3">営業部</td>
</tr>
</tbody>
</table>
<!-- #tablepress-5 from cache -->
<p>現時点では、これが一時テーブル「temp」の中身になる。（1行だけのテーブル）<br clear="none" /><br clear="none" />２．中盤</p>
<p>ここが実質上、再帰をしている部分。</p><pre class="urvanov-syntax-highlighter-plain-tag">union all
select dept.id, dept.parent_id, dept.name 
from temp, dept
where dept.parent_id = temp.id</pre><p>union allはとりあえず置いておいて、その次のselect文の中身を見てみる。</p><pre class="urvanov-syntax-highlighter-plain-tag">select dept.id, dept.parent_id, dept.name 
from temp, dept
where dept.parent_id = temp.id</pre><p>元のテーブル「dept」全体の「parent_id」カラムの内容と、一時テーブル「temp」の「id」の内容が一致しているものを検索する。</p>
<p>つまり、一時テーブルで検索された部署（営業部）を「自分の親だ」と思っている部署が検索される。</p>
<p>今現在の一時テーブルの内容が、</p>

<table id="tablepress-5-no-2" class="tablepress tablepress-id-5">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">2</td><td class="column-2">1</td><td class="column-3">営業部</td>
</tr>
</tbody>
</table>
<!-- #tablepress-5-no-2 from cache -->
<p>で、idは「2」であり、deptからは「parent_id」が「2」の、以下の行が検索される。</p>

<table id="tablepress-3-no-3" class="tablepress tablepress-id-3">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">4</td><td class="column-2">2</td><td class="column-3">営業１課</td>
</tr>
<tr class="row-3">
	<td class="column-1">5</td><td class="column-2">2</td><td class="column-3">営業２課</td>
</tr>
</tbody>
</table>
<!-- #tablepress-3-no-3 from cache -->
<p>というわけで、2行が検索された。</p>
<p>で、ここで忘れてはいけないのは、この段階ではwithで作成される一時テーブル「temp」が「まだ作られてる最中だ」ということ。</p>
<p>つまり、この検索結果が一時テーブル「temp」の内容に書き換わる。</p>
<p>さっきまで1行しかなかった「temp」が、今回の2行の検索結果に書き換わったということ。（ただし、最初の1行のtempは消えない。どこかに保存されている）</p>
<p>そして、さらにこの2行の内容を元にして、先ほどの以下のselect文がまた実行される。</p><pre class="urvanov-syntax-highlighter-plain-tag">select dept.id, dept.parent_id, dept.name 
from temp, dept
where dept.parent_id = temp.id</pre><p>つまり今度は、「親の部署のidが、4か5の部署はないか？」という検索が実行される。</p>
<p>この様に次々に親が書き換わって、その子供が検索されて、その結果またが親になって、その子供が検索されて、それがまた親になって、、、、、というのが繰り返される。</p>
<p>今回の例では、これ以上の子供はないので、ここで子供の検索は終わる。</p>
<p>そして最後に、さっき置いておいたunion all。</p>
<p>これが指定されているので、全ての検索結果（この場合は1行の検索結果と2行の検索結果）が結合されて、以下のようになる。</p>
<p>これで一時テーブル「temp」の作成が完了した。</p>

<table id="tablepress-2-no-2" class="tablepress tablepress-id-2">
<thead>
<tr class="row-1">
	<th class="column-1">id</th><th class="column-2">parent_id</th><th class="column-3">name</th>
</tr>
</thead>
<tbody class="row-striping row-hover">
<tr class="row-2">
	<td class="column-1">2</td><td class="column-2">1</td><td class="column-3">営業部</td>
</tr>
<tr class="row-3">
	<td class="column-1">4</td><td class="column-2">2</td><td class="column-3">営業１課</td>
</tr>
<tr class="row-4">
	<td class="column-1">5</td><td class="column-2">2</td><td class="column-3">営業２課</td>
</tr>
</tbody>
</table>
<!-- #tablepress-2-no-2 from cache -->
<p>以上がwith recursiveを使った再帰検索の中身。</p>
<p>もう一度、with recursiveを使ったselect文全体を見てみる。</p><pre class="urvanov-syntax-highlighter-plain-tag">with recursive temp(id, parent_id, name) as (
    select id, parent_id, name 
    from dept
    where name = '営業部'
    union all
    select dept.id, dept.parent_id, dept.name 
    from temp, dept
    where dept.parent_id = temp.id
)
select * from temp;</pre><p>最後に再帰検索は、where句の条件を間違えると無限ループに陥りやすい為、実行には最新の注意が必要となる。</p>
<p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-2753046354"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-2530406473"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/45/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">45</post-id>	</item>
		<item>
		<title>Postgresqlで月初日、月末日を取得</title>
		<link>https://knowledge.reontosanta.com/archives/14</link>
					<comments>https://knowledge.reontosanta.com/archives/14#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Wed, 12 Nov 2014 05:44:27 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://reontosanta-com.check-netowl.jp/knowledge.reontosanta.com/?p=14</guid>

					<description><![CDATA[Postgresqlで月初日、月末日を取得する &#160; 月初日&#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>Postgresqlで月初日、月末日を取得する</p>
<p>&nbsp;</p>
<h2>月初日の取得</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT DATE_TRUNC('month', now())</pre><p>&nbsp;</p>
<div class="knowl-content" style="margin-top: 40px;" id="knowl-2954840853"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="4196732648" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><h2>月末日の取得</h2>
<p></p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT DATE_TRUNC('month', now() + '1 months') + '-1 days'</pre><p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-4202433512"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-913145994"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/14/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">14</post-id>	</item>
		<item>
		<title>Postgresqlで動的に日付のシフトを行う</title>
		<link>https://knowledge.reontosanta.com/archives/11</link>
					<comments>https://knowledge.reontosanta.com/archives/11#respond</comments>
		
		<dc:creator><![CDATA[mogice]]></dc:creator>
		<pubDate>Wed, 12 Nov 2014 04:42:29 +0000</pubDate>
				<category><![CDATA[Postgresql]]></category>
		<guid isPermaLink="false">http://reontosanta-com.check-netowl.jp/knowledge.reontosanta.com/?p=11</guid>

					<description><![CDATA[現在日からnum_of_daysの日数をシフトした日付を取得する。 &#46;&#46;&#46;]]></description>
										<content:encoded><![CDATA[<p>現在日からnum_of_daysの日数をシフトした日付を取得する。</p><pre class="urvanov-syntax-highlighter-plain-tag">SELECT now() + CAST(num_of_days || 'day' AS INTERVAL)</pre><p>&#8216;day&#8217;部分を変数化すれば、月や週での算出も可能。</p>
<p>日：day<br />
週：week<br />
月：month<br />
年：year</p>
<p>&nbsp;</p>
<div class="knowl-after-content-ad" style="margin-top: 40px;" id="knowl-3020278258"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="2719999442" 
data-ad-format="auto"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div><div class="knowl-after-content-relation" id="knowl-672742741"><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8913642688016174" crossorigin="anonymous"></script><ins class="adsbygoogle" style="display:block;" data-ad-client="ca-pub-8913642688016174" 
data-ad-slot="7848218644" 
data-ad-format="autorelaxed"></ins>
<script> 
(adsbygoogle = window.adsbygoogle || []).push({}); 
</script>
</div>]]></content:encoded>
					
					<wfw:commentRss>https://knowledge.reontosanta.com/archives/11/feed</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">11</post-id>	</item>
	</channel>
</rss>
