按where子句中的条件顺序获取记录

时间:2014-03-14 07:28:04

标签: mysql sql

select id,title,release_date 
from tbl_movies 
where release_date > '2014-02-20' or release_date=''
order by release_date asc
 
"id" |  "title"                "release_date"  
"49" |  "Fandry"               |  ""  
"92" |  "Govinda"              |  ""   
"112"|  "Gadad Jambhal"        |   ""  
"114"|  "Aandhali Koshimbir"   |   ""  
"118"|  "Mee Aani U"           |   ""  
"125"|  "Tapal"                |   ""   
"131"|  "Cappuccino"           |    ""  
"129"|  "Sau Shashi Deodhar"   | "2014-02-21"  
"130"|  "Yellow"               | "2014-03-28" 

我希望最后两条记录首先出现,我不能使用desc,因为结果是基于升序日期,最后两条记录是基于第一个条件,我怎样才能实现它

2 个答案:

答案 0 :(得分:4)

试试这个

SELECT id,title,release_date 
FROM tbl_movies 
WHERE release_date > '2014-02-20' or release_date='' 
ORDER BY CASE WHEN release_date = '""' Then 1 Else 0 End,DATE(release_date) ASC

答案 1 :(得分:3)

您可以在ORDER BY中使用表达式,如下所示:

SELECT id, title, release_date
FROM tbl_movies
WHERE release_date > '2014-02-20' or release_date = ''
ORDER BY (release_date = '') ASC, release_date ASC

release_date = ''表达式返回truefalse,它们分别等于1或0。你首先想要假的,所以我们按升序排序