如何按自定义字段对MySQL ResultSet进行排序?

时间:2014-12-02 10:46:47

标签: mysql sql select sql-order-by

以下是架构和数据:

Create table tblTestSorting (col int);
INSERT INTO tblTestSorting VALUES(2), (5), (3), (6), (4), (7), (1)

我有这样的查询:

SELECT col, 5-col AS 'extra' FROM tblTestSorting ORDER BY 'extra';

我希望将结果排序为' extra'专栏,但是 此查询不会向我提供按'额外'排序的结果柱..

如何实现这个...... ??

5 个答案:

答案 0 :(得分:1)

试试这个:

SELECT col, (5 - col) AS extra
FROM tblTestSorting 
ORDER BY extra;

检查SQL FIDDLE DEMO

<强>输出

| COL | EXTRA |
|-----|-------|
|   7 |    -2 |
|   6 |    -1 |
|   5 |     0 |
|   4 |     1 |
|   3 |     2 |
|   2 |     3 |
|   1 |     4 |

答案 1 :(得分:0)

按类型(asc或desc)给出订单.. 试试这个..

SELECT col, 5-col AS extra FROM tblTestSorting ORDER BY col ASC

答案 2 :(得分:0)

两种方式

SELECT col, 5-col AS 'extra' FROM tblTestSorting ORDER BY 5-col;


SELECT col, 5-col AS 'extra' FROM tblTestSorting ORDER BY 2;

答案 3 :(得分:0)

试试这个:

 SELECT col, 5-col AS 'extra' FROM tblTestSorting ORDER BY 'extra' ASC

 SELECT * FROM (SELECT col, 5-col AS 'extra' FROM tblTestSorting) as t ORDER BY t.'extra' ASC

答案 4 :(得分:0)

解决方案1 ​​

  

选择*来自(SELECT col,5-col AS'额外'FROM tblTemp)订单额外

或解决方案2

  

SELECT col,5-col AS`extra` FROM tblTemp order by“extra`