MySQL查询带模数的ORDER BY

时间:2016-04-22 16:59:23

标签: mysql sql sql-order-by

我的SELECT查询

SELECT ID, NAME  FROM TBL_USER ORDER BY ID % 2, ID % 3

输出:

   ID   |  NAME 
--------|---------
    6   |   AB
    12  |   BC
    4   |   XY
    10  |   YZ
    2   |   C1
    8   |   C2
    3   |   A3
    9   |   MN
    1   |   K2
    7   |   WQ
    13  |   OP
    5   |   HJ 
    11  |   KN

我对ORDER BY如何与MODULUS(%)一起工作感到困惑。这个订单是如何生成的?

2 个答案:

答案 0 :(得分:3)

如果您将查询更改为

SELECT ID, NAME, ID %2, ID %3  FROM TBL_USER ORDER BY ID % 2, ID % 3

包含ORDER BY对其进行操作的值变得清晰:

+------+------+-------+-------+
| ID   | NAME | ID %2 | ID %3 |
+------+------+-------+-------+
|    6 | AB   |     0 |     0 |
|   12 | BC   |     0 |     0 |
|    4 | XY   |     0 |     1 |
|   10 | YZ   |     0 |     1 |
|    2 | C1   |     0 |     2 |
|    8 | C2   |     0 |     2 |
|    9 | MN   |     1 |     0 |
|    3 | A3   |     1 |     0 |
|    1 | K2   |     1 |     1 |
|    7 | WQ   |     1 |     1 |
|   13 | OP   |     1 |     1 |
|    5 | HJ   |     1 |     2 |
|   11 | KN   |     1 |     2 |
+------+------+-------+-------+

答案 1 :(得分:1)

假设您了解MOD的工作原理,这里的表格显示值实际上是正确的顺序。您可以通过将select语句更改为:

来自行生成此项
SELECT ID, ID % 2, ID % 3, NAME FROM TBL_USER ORDER BY ID % 2, ID % 3;

   ID   |  ID % 2  |  ID % 3  |  NAME 
--------|----------|----------|--------
    6   |     0    |     0    |   AB
    12  |     0    |     0    |   BC
    4   |     0    |     1    |   XY
    10  |     0    |     1    |   YZ
    2   |     0    |     2    |   C1
    8   |     0    |     2    |   C2
    3   |     1    |     0    |   A3
    9   |     1    |     0    |   MN
    1   |     1    |     1    |   K2
    7   |     1    |     1    |   WQ
    13  |     1    |     1    |   OP
    5   |     1    |     2    |   HJ 
    11  |     1    |     2    |   KN