Mysql 如何在order by语句中按DESC放置字符串值
我用mySQL写了一个程序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
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的优点是您希望查询将使用索引