1
0

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 1 year has passed since last update.

環境

CentOS7
PostgreSQL 11.18

試してみた

まずはそれぞれのテーブルにあるデータを確認しておこうっと。

-- products
postgres=# select * from products;
  name  | price |     etc      
--------+-------+--------------
 りんご |   150 | 青森産
 メロン |  3000 | 北海道産
 ぶどう |   300 | 
 みかん |    80 | 
      |   300 | 
 バナナ |   250 | フィリピン産
(6 )

-- orders
postgres=# select * from orders;
  name  |  farm_name   | arrival_date | order_num 
--------+--------------+--------------+-----------
 りんご | 津軽ファーム | 2012-07-31   |        26
 みかん | みかん園     | 2012-07-31   |        16
 みかん | 紀州果樹園   | 2012-07-31   |        12
 ぶどう | 津軽ファーム | 2012-07-31   |         8
      | 梨園         | 2012-07-31   |        14
 メロン | メロン農園   | 2012-07-31   |        13
(6 )

それぞれ6行ずつデータが入っていた。
まずはfrom句での交差結合だ。

postgres=# select * from products, orders;
  name  | price |     etc      |  name  |  farm_name   | arrival_date | order_num 
--------+-------+--------------+--------+--------------+--------------+-----------
 りんご |   150 | 青森産       | りんご | 津軽ファーム | 2012-07-31   |        26
 りんご |   150 | 青森産       | みかん | みかん園     | 2012-07-31   |        16
 りんご |   150 | 青森産       | みかん | 紀州果樹園   | 2012-07-31   |        12
(中略)
 バナナ |   250 | フィリピン産 | ぶどう | 津軽ファーム | 2012-07-31   |         8
 バナナ |   250 | フィリピン産 |      | 梨園         | 2012-07-31   |        14
 バナナ |   250 | フィリピン産 | メロン | メロン農園   | 2012-07-31   |        13
(36 )

productsのりんごに対して、ordersのりんご、みかん、みかん、ぶどう〜と結合していくのか。
CROSS JOINを使っても同じように取得できるぞ。

postgres=# select * from products cross join orders;
  name  | price |     etc      |  name  |  farm_name   | arrival_date | order_num 
--------+-------+--------------+--------+--------------+--------------+-----------
 りんご |   150 | 青森産       | りんご | 津軽ファーム | 2012-07-31   |        26
 りんご |   150 | 青森産       | みかん | みかん園     | 2012-07-31   |        16
(中略)
 バナナ |   250 | フィリピン産 | ぶどう | 津軽ファーム | 2012-07-31   |         8
 バナナ |   250 | フィリピン産 |      | 梨園         | 2012-07-31   |        14
 バナナ |   250 | フィリピン産 | メロン | メロン農園   | 2012-07-31   |        13
(36 )

外部結合よりも正直シンプルだからわかりやすいね。
ただ、使い所はいまいち思いつかない。

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?