SQL ORDER BY查询

时间:2011-05-31 02:48:40

标签: mysql sql sql-order-by

我希望我的表格rcarddet按“SDNO”(非主键)按升序排序,但“0”除外。所以结果应该是:

1
1 
2
.
.
10
0
0

我的查询现在是:

SELECT * 
  FROM `rcarddet` 
 WHERE `RDATE` = '2011-05-25' 
   AND `RCNO` = '1' 
   AND `PLACE` = 'H' 
   AND `SDNO` != 0 
ORDER BY `rcarddet`.`SDNO` ASC;

2 个答案:

答案 0 :(得分:6)

最简单的方法

  SELECT * FROM rcarddet   
   WHERE RDATE = '2011-05-25' and RCNO = '1'and PLACE = 'H'  
ORDER BY CASE  
           WHEN rcarddet.SDNO  = 0 THEN [max_number_for_the_type_of_SDNO]  
           ELSE rcarddet.SDNO   
         END ASC  

答案 1 :(得分:4)

SELECT * 
  FROM `rcarddet` 
 WHERE `RDATE` = '2011-05-25' 
   AND `RCNO` = '1' 
   AND `PLACE` = 'H' 
ORDER BY
  `SDNO` = 0,
  `SDNO`;