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?

Laravel Migrationで触った新しいSQL構文メモ

Last updated at Posted at 2025-09-10

Laravelのマイグレーションでデータ再計算処理を書いたときに、いくつか「へぇ〜こう書くのか」というSQL構文に出会ったので簡単にまとめ

1. COALESCE()

COALESCE(w.filling_kg, 0)
  • 意味:NULLを別の値に置き換える
  • この場合「fillingがNULLなら0として扱う」
  • 計算時にNULLが混ざると全体がNULLになってしまうので必須

2. ROUND(式, 桁数)

ROUND( ( ... )::numeric, 2 )
  • 意味:四捨五入して小数点以下を指定桁数に丸める
  • ::numeric は型キャスト(PostgreSQL)。整数や浮動小数から精度の高い数値型に変換する。
    • 例:123.456 → ROUND(..., 2) = 123.46

3. サブクエリでの CASE 式

SET co2 = (
  SELECT CASE
    WHEN r.gwp IS NULL THEN NULL
    ELSE ROUND((w.discharge_kg * r.gwp) / 1000, 3)
  END
  FROM degital d
  LEFT JOIN retaurants r ON r.id = d.restaurant_id
  WHERE d.id = w.degital_id
)
  • CASE ... WHEN ... THEN ... ELSE ... END で条件分岐。
  • この例では「restaurantのGWPがNULLならco2もNULL、そうでなければ計算結果を入れる」

4. ::型 キャスト

(... )::numeric

  • PostgreSQL特有の書き方。
  • 値を指定の型にキャスト(変換)する。
  • numeric は任意精度の小数を扱える型。

5. IN (...) のプレースホルダ

$in = implode(',', array_fill(0, count($types), '?'));
...
WHERE w.work_type IN ($in)
  • PHP側で ?, ?, ? を生成 → バインディングする。
  • 動的に「このリストの中に含まれるか?」を判定できる。

6. DB::update() の戻り値

$updatedDischarge = DB::update("UPDATE ...", $types);
  • 実は「更新件数」が返る。
  • なので echo で「何件更新されたか」をログに出せる。

まとめ

今回新しく学んだのは:

  • NULL対策は COALESCE
  • 丸めは ROUND + ::numeric
  • 条件分岐は CASE
  • キャストは ::型(PostgreSQL)
  • IN (?) はPHPでプレースホルダを生成
  • DB::update は件数が返る
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?