Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在order by语句中按DESC放置字符串值_Mysql_Sql - Fatal编程技术网

Mysql 如何在order by语句中按DESC放置字符串值

Mysql 如何在order by语句中按DESC放置字符串值,mysql,sql,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; E

我用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是参数):


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

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

下面是一个技巧,您可以使用
案例
表达式:

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;

下面是一个技巧,可用于
案例
表达式:

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;

你有两个选择。一种是通过摆弄命令:

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的优点是您希望查询将使用索引。

您有两个选择。一种是通过摆弄命令:

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的优点是您希望查询将使用索引