如何按语句按顺序放置DESC的字符串值

时间:2016-11-17 02:05:20

标签: mysql sql

我在mySQL中编写了一个程序,

IN `para`  varchar(4)
BEGIN
    #Routine body goes here...

if (para = 'asc') THEN

SELECT officeCode, city, country
from offices
ORDER BY country ;

ELSE

SELECT officeCode, city, country
from offices
ORDER BY country DESC;


END if;
END

那段代码还可以,但是我想知道是否还有其他方法可以缩短,比如这样(调用程序时para是参数):

BEGIN
SELECT officeCode, city, country
from offices
ORDER BY country *para* ;

END
--------but this is not work-------

3 个答案:

答案 0 :(得分:0)

如果在您的解决方案中有效,您可以使用您选择的任何脚本语言,基于para轻松动态生成查询文本。

答案 1 :(得分:0)

这是一个可以与CASE表达式一起使用的技巧:

SELECT officeCode,
       city,
       country
FROM offices
ORDER BY CASE WHEN para = 'asc'  THEN Country ELSE '1' END ASC,
         CASE WHEN para != 'asc' THEN Country ELSE '1' END DESC;

答案 2 :(得分:0)

您有两种选择。一个是摆弄order by

SELECT officeCode, city, country
FROM offices
ORDER BY (CASE WHEN para = 'asc' THEN country END),
         country DESC;  -- you could use a `case` here but it is not necessary

或者,您可以使用预先准备的声明:

set @sql = '
SELECT officeCode, city, country
FROM offices
ORDER BY para [dir]';

set @sql = replace(@sql, '[dir]', (case when para = 'asc' then 'asc' else 'desc' end));

prepare q from @sql;
execute q;

动态SQL的优点是您希望查询将使用索引。