mysql存储过程中的order子句中的case条件

时间:2014-12-03 11:25:03

标签: mysql stored-procedures

示例存储过程:

DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN yr_order tinyint(1))
 BEGIN
 SELECT * 
 FROM offices
 WHERE country LIKE 'A';
 ORDER BY
 CASE yr_order
        WHEN 1 THEN updated
        WHEN 2 THEN likes
        ELSE 1 END  
 ASC
 END //
DELIMITER ;

yr_order是存储过程参数。在条件之后放置ASC时查询正常:

  CASE yr_order
        WHEN 1 THEN updated 
        WHEN 2 THEN likes 
        ELSE 1 END  
  ASC

我可以为每个条件设置不同的排序顺序:

  CASE yr_order
        WHEN 1 THEN updated ASC
        WHEN 2 THEN likes ASC
        WHEN 3 THEN updated DESC
        WHEN 4 THEN likes DESC
        ELSE 1 END  

我的语法错误。是否有办法对每种情况使用不同的排序?

1 个答案:

答案 0 :(得分:1)

不,你不能,但你可以这样做:

CASE yr_order
        WHEN 1 THEN updated 
        WHEN 2 THEN likes 
        WHEN 3 THEN -updated 
        WHEN 4 THEN -likes 
        ELSE 1 END  
ASC

假设更新,喜欢是数字。如果他们不是,你可以做类似的事情:

ORDER BY

   CASE yr_order
            WHEN 1 THEN updated 
            WHEN 2 THEN likes 
            ELSE 1 END  
    ASC,
   CASE yr_order

            WHEN 3 THEN updated 
            WHEN 4 THEN likes 
            ELSE 1 END  
    DESC