LoginSignup
0
0

More than 5 years have passed since last update.

PHPのmax関数をSQLで実現したい

Last updated at Posted at 2018-07-25
$a = 1;
$b = 3;
$c = max($a, $b);
$d = 2;

if ($c > $d) {
  print 'ok';
} else {
  print 'ng';
}

これ、SQLで実現しようと思うとめっちゃ面倒くさい

select case when a > b then a else b end

でも、null が入ってたら 演算結果 null になるんですよね……

select case when coalesce(a, 0) > coalesce(b, 0) then a else b end
select
    case
        when (select case when coalesce(a, 0) > coalesce(b, 0) then a else b end) > d
        then 'ok'
        else 'ng'
        end;

まだなんとかなったけど、演算とかいろいろ噛むと地獄になってくるよね

select max(t.a) from (select 1 as a union select 2 as a) t

こうすると、1つの値を2回かかなくてよくなる、PHPのmax関数と同じ挙動にできる

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