ORDER BY复杂

时间:2012-12-15 00:19:40

标签: mysql sql-order-by

我有一个mysql_query:select * from table ORDER BY v1, v2 ASC

可以进行查询以对v1v2进行排序,如下所示?

+---------------+-----------------------+------+-----+
| id            | name                  | v1   | v2  | 
+---------------+-----------------------+------+-----+
| 1             | a                     | 1    |  A  |
| 2             | a                     | 2    |  B  |
| 3             | a                     | 3    |  C  |
| 4             | a                     | 1    |  A  |
| 5             | a                     | 2    |  B  |
| 6             | a                     | 3    |  C  |
| 7             | a                     | 1    |  A  |
| 7             | a                     | 2    |  B  |
| 7             | a                     | 3    |  C  |
+---------------+-----------------------+------+-----+

SQL fiddle

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

Select id, name, v1, v2, (v1 + ASCII(v2)) as mySum
from table
order by mySum

ASCII http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_ascii

答案 1 :(得分:1)

您需要另一列进行排序。你必须告诉MySQL为什么id 1,2,3在4,5,6之前出现。如果您有另一列,例如1表示1,2,3,2表示4,5,6等,您可以按以下顺序排序:

ORDER BY missing_col, v1, v2