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

打赏

免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2022 CODEPRJ.COM