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

UNIONってなに?何がうれしい?

Posted at

UNIONとは

UNION = 複数のSELECT結果を“縦にくっつける(上下に連結)” 操作

  • UNION 同じ形(列数・並び・型)にそろえた結果をまとめて1本にする
  • JOIN テーブルを横方向に結合(列が増える)←別物!

いつ使う

  • 例:)作業テーブル(works) と 点検テーブル(inspections) を日付順でひとつの一覧にしたい
  • ダウンロード / 一覧画面で「種類の違うデータをまとめて並べたい」ときに便利

いちばん簡単なコード例(Query Builder)

use Illuminate\Support\Facades\DB;

$works = DB::table('works')
  ->select('id', 'work_date as date', DB::raw("'work' as type"));

$insps = DB::table('inspections')
  ->select('id', 'inspection_date as date', DB::raw("'inspection' as type"));

$rows = $works
  ->unionAll($insps)          // ← 重複を消さず“速い”縦連結(初心者はまずこれでOK)
  ->orderBy('date')           // ← まとめた後で並び替え
  ->get();
  • これで id / date / type という同じ形の行が、両テーブル分まとまって日付順で取れる

UNION と UNION ALL の違い

  • UNION:重複行を削除(そのぶん遅い)
  • UNION ALL:重複行をそのまま(速い・よく使う)

異なるテーブルを単に「合体」したいだけなら UNION ALL でOK。

ハマりやすいポイント

  • 列数・順番・型をそろえる:上の例のように、同じ列名/型に揃える(as date, as type)
  • 並び替えは“外側”で:UNIONした後で orderBy をする
  • Eloquentでも同じ発想:Model::select('id', DB::raw("... as date")) で列を揃えてから union します

まとめると

  • UNION = 縦に合体、JOIN = 横に合体
  • 異なるテーブルを1本の一覧にしたい時に使う
0
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
0
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?