MySQL条件ASC / DESC

时间:2015-04-17 19:47:48

标签: mysql sql procedure mariadb

我正在尝试创建一个存储过程,以便我可以按升序或降序轻松地对某些数据进行排序。我已经浏览了整个互联网,最后得到 MySQL 来接受我想要做的事情,但现在当我调用该程序时,它会产生垃圾数据。如果我自己运行查询,一切都很完美。我究竟做错了什么?这是我的代码:

DROP PROCEDURE IF EXISTS OrderPlants;

DELIMITER //

CREATE PROCEDURE OrderPlants (IN OrderSeq CHAR(4))

BEGIN

SELECT Location.State, Operator.Name, Plant.TotalOutput
FROM Plant

INNER JOIN Location
ON Plant.LocationID = Location.ID

INNER JOIN Operator
ON Plant.OperatorID = Operator.ID

ORDER BY 
CASE WHEN @OrderSeq = 'ASC' THEN Plant.TotalOutput END ASC,
CASE WHEN @OrderSeq = 'DESC' THEN Plant.TotalOutput END DESC

LIMIT 5;

END //

DELIMITER ;

这是它产生的输出:

MariaDB [nuclear]> call orderplants ('ASC');
+-------+-----------------------------+-------------+
| State | Name                        | TotalOutput |
+-------+-----------------------------+-------------+
| FL    | Florida Power & Light Co.   |        6040 |
| IA    | CORN BELT POWER COOP        |          38 |
| KY    | DUKE ENERGY KENTUCKY INC    |         648 |
| IN    | JASPER MUNICIPAL UTIL (IN)  |          15 |
| OH    | FIRSTENERGY GENERATION CORP |          18 |
+-------+-----------------------------+-------------+
5 rows in set (0.01 sec)

Query OK, 0 rows affected (0.04 sec)

如果使用 DESC 输入调用过程,那么数据应该是这样的:

+-------+--------------------------------+-------------+
| State | Name                           | TotalOutput |
+-------+--------------------------------+-------------+
| AZ    | Arizona Public Service Company |       11970 |
| AL    | Tenessee Valley Authority      |       10374 |
| PA    | PPL Susquehanna, LLC           |        7904 |
| TX    | STP Nuclear Operating Co.      |        7706 |
| SC    | Duke Energy Carolinas, LLC     |        7704 |
+-------+--------------------------------+-------------+
5 rows in set (0.00 sec)

ASC 输入应该是什么输出:

+-------+-------------------------------+-------------+
| State | Name                          | TotalOutput |
+-------+-------------------------------+-------------+
| PA    | KOPPERS CO                    |           3 |
| MN    | NORTHERN STATES POWER CO (MN) |           7 |
| MN    | AMERICAN CRYSTAL SUGAR CO     |           8 |
| IA    | MIDAMERICAN ENERGY CO         |           8 |
| IN    | JASPER MUNICIPAL UTIL (IN)    |          15 |
+-------+-------------------------------+-------------+
5 rows in set (0.01 sec)

2 个答案:

答案 0 :(得分:1)

你可以尝试这样的事情:

ORDER BY if(@OrderSeq = 'ASC', Plant.TotalOutput, -Plant.TotalOutput)

这里是样本小提琴http://sqlfiddle.com/#!9/60b4e/7

答案 1 :(得分:0)

中删除@
CASE WHEN @OrderSeq = 'ASC' THEN Plant.TotalOutput END ASC

CASE WHEN @OrderSeq = 'DESC' THEN Plant.TotalOutput END DESC

解决了问题