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.

【SQL】何度も使うテーブルはWITH句を活用する

Posted at

問題の背景

SQLである初心者は、使いたいテーブルがあったらBigQuery上で結合を行った後一つ一つテーブルやビューとして保存してからJOINを行っていた。
これでは後から見た時にどのテーブルを結合したのか、いちいち探しにいく必要がある。
作成したテーブルを今後も使うことがあるのであれば、それでも構わないが今回限りしか使わない、且つ今回は何度も使用するという場合はWITH句を使って一つのビューの中でテーブルを作ってしまうのが早い。

WITH句の使い方。

WITH句はいわゆるサブクエリである。
記述方法は以下のようになる。

SQL
WITH テーブル名 AS (SELECT ... FROM ...)

より詳細な使い方としては以下のようになる。

今回はusersテーブルとusers_detailsという二つのテーブルを結合し、IDが1から100までのユーザーを抽出したテーブル"target_users"とproductsテーブルとproducts_detailsテーブルを結合したテーブル"products"をWITH句で作成する。

SQL

WITH
    target_users AS (
        SELECT users.name, users.id, users_details.registered_at
        FROM `labokgs_project/users` users
        JOIN users_details users_details
        USING(id)
        WHERE id BETWEEN 1 and 100
        ),

    products AS (

        SELECT procuts.name, products.id, products_details.url
        FROM `labokgs_project/products` products
        JOIN products_details
        USING(id)

        )
SELECT ...
FROM ...

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?