PostgreSQLで複数のテーブルを結合して処理する方法

2007年11月26日 03:15 PostgreSQLで複数のテーブルを結合して処理する方法

今日は久々に旧ブログから記事を引っ張ってきました。

以下は二年以上前に書いたブログ記事の転載です。


新鮮なネタがないので、ストックの中からPostgreSQLネタでも。
というわけで、PostgreSQLで複数のテーブルを結合して処理する方法のメモです。

「複数のテーブルを結合して集計する」というのがどういう意味かと言うと、例えばまず会員制のショッピングサイトなどでユーザーの情報を管理するDBがあると仮定します。
で、一つ目のテーブル「TABLE1」には下記のように、ユーザーID・ユーザーの氏名・ユーザーのメールアドレス等の基本情報が格納されているとします。

TABLE1
UserID UserName MailAddress
Amethyst 鬼瓦 権三郎 amethyst@amethyst-web.org
Alexandrite 俵田山 兼松 alexandrite@amethyst-web.org
Sapphire 平等院 鳳凰堂 sapphire@amethyst-web.org

次に、二つ目のテーブル「TABLE2」には、各ユーザーの購入商品の情報が格納されているとします。
例えば、注文ID・注文者のユーザーID・商品名・商品価格etc。

TABLE2
OrderID UserID ItemName ItemPrice
1 Amethyst 扇風機 2980
2 Amethyst エアコン 99800
3 Sapphire コーヒーメーカー 2800
4 Amethyst 電気コタツ 5800
5 Alexandrite 上戸彩写真集 4800
6 Sapphire マグカップ 1200
7 Alexandrite エロマンガ 980

さて、上記の注文商品の情報が格納されたTABLE2のデータを元に、注文したユーザー宛に一括で受注確認のメールを送信するプログラムを作りたい時、どうすれば良いでしょうか。

単純に処理しようと思えば、まずTABLE2のデータを一行ずつ取得し、その情報の中からユーザーIDを取得し、次にそのユーザーIDをキーにしてTABLE1からメールアドレスを取得、という流れになります。
perlで書くと、下記のような感じ

#-- TABLE2のデータを取得
$SQLstat1 = $DB->prepare("select OrderID, UserID, ItemName, ItemPrice from TABLE2");
#-- 一行ずつ処理する
while(@DATA = $SQLstat1->execute){
    #-- 取得したデータを変数にセット
    ($OrderID,$UserID,$ItemName,$ItemPrice) = @DATA;
    #-- $UserIDをキーにしてTABLE1のデータを取得
    $SQLstat2 = $DB->prepare("select UserName, MailAddress from TABLE1 where UserID = '$UserID'");
    #-- 取得したデータを変数にセット
    ($UserName,$MailAddress) = $SQLstat->execute;
    #-- 以下にメール送信の処理が入る
    &SendMail;
}

※上記の処理の場合は、実際にはプレースホルダを使った方が良いと思いますが、ここでは処理の流れをわかりやすくするために敢えてこういう記述にしました。

さて、上記のスクリプトの場合は一つ目のselect文の中で何度も別のselect文を発行していることになります。
が、select文にinner joinという句を使うと、一度のSQL文で上記の処理を済ますことができます。
↓こんな感じ。

#-- TABLE2のデータを元にTABLE1からUserIDをキーにしてデータを取得
$SQLstat = $DB->prepare("select TABLE2.OrderID, TABLE2.UserID, TABLE2.ItemName,
 TABLE2.ItemPrice, TABLE1.UserName, TABLE1.MailAddrss
 from TABLE2 inner join TABLE1 on TABLE2.UserID = TABLE1.UserID");
#-- 一行ずつ処理する
while(@DATA = $SQLstat->execute){
    #-- 取得したデータを変数にセット
    ($OrderID,$UserID,$ItemName,$ItemPrice,$UserName,$MailAddress) = @DATA;
    #-- 以下にメール送信の処理が入る
    &SendMail;
}

上記スクリプトの
from TABLE2 inner join TABLE1 on TABLE2.UserID = TABLE1.UserID
の部分がポイントです。
これは「TABLE2とTABLE1を結合するよ。条件として"TABLE2のUserIDとTABLE1のUserIDが同じ"データを結合してね」
ということです。
ちなみに、上記select文で出てくる TABLE2.OrderID とか TABLE1.UserID とかはそれぞれ「TABLE2内のOrderID」「TABLE1内のUserID」を表します。

このinner join句は、select文だけではなくupdate文にも使えますので何かと便利です。
delete文には使った記憶がないのでよくわかりません。多分使えるんじゃないですかね?

阿部辰也へのお仕事のご依頼・お問合せはこちら

Twitter始めました。Followはお気軽にどうぞ。

関連するブログ記事
スポンサード リンク
カテゴリー
PostgreSQL | perl/CGI
タグ
inner join | perl | PostgreSQL | RDBMS | SQL | コマンドライン | シェル
現在位置
TOP > Web制作技術 > PostgreSQL > PostgreSQLで複数のテーブルを結合して処理する方法
前のブログ記事
「お気に入りに追加」「ブックマークに追加」ボタンのまとめ [2007年11月25日 17:12]
次のブログ記事
PostgreSQL で連番の数字のフィールドを作る方法 (sequence について) [2007年12月 1日 23:59]

トラックバック(0)

このブログ記事に対するトラックバックURL:

コメント(25)

money mutual [2014年9月 2日 11:28]

qkvoyay http://paydayloansvmn.com/ money mutual

payday loans [2015年1月29日 22:43]

qfwzna http://paydayloansrna.com/ payday loans

payday loans [2015年7月 1日 02:25]

efowrud http://paydayloansnxf.com/ payday loans

viagra [2016年4月20日 20:10]

Hello!

viagra [2016年4月20日 20:11]

Hello!

nike 0 [2016年4月28日 20:13]

Anti Doping Agency banned Armstrong from the sport for life over alleged use of PEDs.

nike 2 [2016年4月28日 20:14]

Just browse through the online galleries of SunglassesUK and you are sure to find an overwhelming number of the most up to date designer and sports sunglasses including Tiffany sunglasses, Chanel sunglasses, Prada sunglasses, Oakley sunglasses, Rayban sunglasses, and even Oakley goggles and Bolle ski goggles.

nike 4 [2016年4月28日 20:14]

When something distinct is present in a person or object and if that give tremendous enjoyment to the one who has and to the one who sees it, then it is termed as beauty.

nike 2 [2016年4月28日 20:15]

And the vents don shoot air into your eyes; it more of a gentle circulation of freshness.

purple air max 2014 [2016年7月 3日 02:54]

Guests representing press outlets at the event were able to choose a free pair of Oakley sunglasses that they could either create at the Custom Bar or pick from the selection on display.
purple air max 2014 http://www.officedepotc.com/r035/

air max 2014 purple [2016年7月 3日 02:54]

To become a thing what this means is of which a electronic slr lenses currently been laminated with large collections enabling only vertically polarized rays to go into the eyes.
air max 2014 purple http://www.marthastewartc.com/r285/

2015 nike air max [2016年7月 3日 02:55]

Related ArticlesCreative and Inexpensive Valentines Day Gift Idea.
2015 nike air max http://www.murdochinstitutew.com/r219/

air max 2014 cheap [2016年7月 3日 02:55]

According to court documents, the two were drinking while off duty at the bar when a 29 year old man refused to leave the pub.
air max 2014 cheap http://www.kaptestcu.com/r076/

2014 black nike air max [2016年7月 3日 02:56]

Theyre at a point where they are about to introduce a transition lens that where you go outside its your sunglasses, and when you go into the movie theater it transitions into 3 D glasses.
2014 black nike air max http://www.kaptestc.com/r272/

2014 air max womens [2016年7月 3日 14:10]

We have great fashion style, to display suitable for any decor.

wmns air max 2014 [2016年7月 3日 14:11]

The Yoplait site features a way to send an e card to increase awareness.

mens 2014 nike air max [2016年7月 3日 14:12]

Registration closes Aug.

air max 2014 nike [2016年7月 3日 21:20]

We put real technology in our Fishing Specific eyewear.
air max 2014 nike http://www.gmc-o.com/n215/

yeezy boost 350 pirate black [2016年7月10日 20:58]

Now I have that name.
yeezy boost 350 pirate black http://www.yeezyboost350pirateblack.in.net/

yeezy boost 350 [2016年7月10日 20:59]

Since 1980, Oakley has begun to manufacture sunglasses, which has also led to the coming of Replica Oakley sunglasses.
yeezy boost 350 http://www.yeezyboost350adidas.in.net/

Yeezy Boost 350 For Sale [2016年7月10日 20:59]

Oakley t shirts are a sampling of the brands creative vision and some of the best ones are a gray NYC subway map t shirt, a white v neck t shirt with a colorful Oakley NYC logo, and a white Brooklyn Bridge t shirt.
Yeezy Boost 350 For Sale http://www.yeezyboost350forsale.in.net/

Yeezy Boost 350 [2016年7月10日 20:59]

Designer products such as Oakley Sunglasses are rare to find and such sites that offer quality with a reasonable price tag are worth keeping your eye on.
Yeezy Boost 350 http://www.blackyeezyboost350.in.net/

air max 2015 womens pink [2016年9月 2日 16:29]

They are some of Oakleys most affordable sunglasses and offer 100% UV protection with interchangeable lenses for different conditions.

air max 2016 electric green [2016年9月 2日 16:31]

Heavy duty wheels allow convenient, reduce stress, and the telescopic handle in your arm for easy mobility so.

fvkehp [2017年1月14日 00:43]

Sildenafil 100mg viagra price relaxes muscles originate in the walls of blood vessels and increases blood air pocket to particular areas of the body.

コメントする


画像の中に見える文字を入力してください。

 

このブログについて

阿部辰也

Webコンサルタントやシステムエンジニア、執筆業などをやっている、グッドホープ代表・阿部辰也のブログです。
Web技術系のTipsから仕事の話、趣味の話まで色々と。
人生は所詮生まれてから死ぬまでの壮大な暇つぶし。
だったら有意義に暇をつぶして生きましょー。

阿部辰也へのお仕事のご依頼・問合せはこちらからどうぞ。

Twitter: @t_abe
読書メーター: ID:Tatsuya

このブログのサイトマップ
このブログのはてなブックマーク数

Feed/RSS購読

タグクラウド

最近のトラックバック

阿部辰也の著書

77のキーワードで知る インターネットで稼ぐ 図解 ブログ・メルマガ・Webサイト構築の基本

77のキーワードで知る インターネットで稼ぐ 図解 ブログ・メルマガ・Webサイト構築の基本

頑張って書いたのに、出版後すぐに出版社が倒産して印税も貰えずじまいで俺涙目(笑)。

Powered by Movable Type 5.02

スポンサード リンク

はてなブックマーク



あわせて読みたい

t-abeの今読んでる本

t-abeの最近読んだ本

t-abeの今やってるゲーム

t-abeの最近やったゲーム