LoginSignup
2
2

More than 5 years have passed since last update.

unionを使って一時テーブルっぽい動作をさせる

Posted at

Railsでenumを定義して使用しているけど、急遽SQL使ってデータをいい感じに書き出したいときに有用。

まずはこれを見て欲しい

mysql> select 1 as id, 'hoge' as name union select 2, 'foo' union select 3, 'bar';
+----+------+
| id | name |
+----+------+
|  1 | hoge |
|  2 | foo  |
|  3 | bar  |
+----+------+

# クエリ部分を整形してみた
select 
  1 as id, 'hoge' as name
union select
  2, 'foo' 
union select
  3, 'bar';

あたかもテーブルがあるかのような出力になった!

で、使いみちはあるの?

JOINができる。

例として、

users
  id
  name
  state_id

があるとする。しかし、何らかの事情でstate_idに対するテーブルがない。そんなとき。

mysql> select users.id, users.name, states.name as state_name from users left join (select 1 as id, 'hoge' as name union select 2, 'foo' union select 3, 'bar') as states on (users.state_id = states.id);
+------+--------+------------+
| id   | name   | state_name |
+------+--------+------------+
|    1 | taro   | hoge       |
|    2 | hanako | foo        |
+------+--------+------------+

# 整形
select users.id, users.name, states.name as state_name 
from users 
  left join (
    select 1 as id, 'hoge' as name
    union select 2, 'foo'
    union select 3, 'bar'
  ) as states on (users.state_id = states.id);

いい感じに出力できた!

総評

使う機会はあまりない。ただ、知っていおいて損はないかも。

2
2
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
2
2