MySQL case when 使用

case when 自定义排序时的使用
根据 case when 新的 sort字段排序

    case 
    when t2.status = 4
    and t2.expire_time>UNIX_TIMESTAMP()
    and t2.expire_time<UNIX_TIMESTAMP(DATE_ADD(NOW(),INTERVAL 60 day)) then 4
        when `status` = 2  then 3
        when `status` = 3 then 2
        when t2.status = 4
        and t2.expire_time>UNIX_TIMESTAMP(DATE_ADD(NOW(),INTERVAL 60 day))
        and t2.expire_time<UNIX_TIMESTAMP(DATE_ADD(NOW(),INTERVAL 1 year)) then 1
    else 0
    end sort     
    
     $query->orderBy('sort desc ,t2.expire_time desc,t2.created_at desc');
    
  • 当colume 与condition 条件相等时结果为result
case colume 
    when condition then result
    when condition then result
    when condition then result
else result
end

image

  • 当满足某一条件时,执行某一result

case  
    when condition then result
    when condition then result
    when condition then result
else result
end

image

  • 当满足某一条件时,执行某一result,把该结果赋值到new_column_name 字段中
case  
    when condition then result
    when condition then result
    when condition then result
else result
end new_column_name

case when 用在select 语句中,新的字段new_column_name可以用来排序,但是不能用在where中

image
image
end 后面加as new_colume_name
image

posted @ 2017-12-15 11:18  哦先生  阅读(447978)  评论(2编辑  收藏  举报