0
0

More than 1 year has passed since last update.

MysqlでNULLのカラムをカウントする方法

Last updated at Posted at 2021-10-19

はじめに

outer joinしたテーブルでNULLを含むカラムをカウントした結果をorderByで並び替え用とした時にNULLのレコードがカウントされなかった。
NULLのレコードもカウントする方法を備忘として記録する。

事例

tableA ※nameはユニークとする

id name
1 aaa
2 bbb

tableB

id point
1 10
1 20
DB::table('tableA')
    ->leftjoin('tableB', 'tableB.id', '=', 'tableA.id')
    ->orderBy(DB::raw('count(point)')
    ->groupBy('tableA.id')
    ->get();

Laravelにて上記クエリビルダを実行すると下記のテーブルが得られる。

id name point
1 aaa 30

IFNULLを使用することでid=2も取得することができる。

DB::table('tableA')
    ->leftjoin('tableB', 'tableB.id', '=', 'tableA.id')
    ->orderBy(DB::raw('count(IFNULL(point, 0))')
    ->groupBy('tableA.name')
    ->get();

※tableBにid=2が無いため、idでgroupByをするとエラーとなった。

実行結果

id name point
2 bbb 0
1 aaa 30

IFNULLの使い方

IFNULL('カラム名', 'NULLを置き換えたい値')

※Mysqlではない場合、NULLの置き換えはIFNULLとは限らない。

0
0
1

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