はじめに
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とは限らない。