如何在MySQL中进行不同的排序?

时间:2018-04-16 07:42:27

标签: mysql sql mysql-workbench

我有这个:

SELECT put_id,ut_id,cm_tx,da,un FROM TA

ut_id  | put_id  |        cm_tx             | da         |   un
 ------|---------|--------------------------|------------|--------
 21    | 21      |  was good                | 1523190974 |  Jonah
 22    | 21      |  thx                     | 1523197793 |  Sara
 23    | 23      |  that was good post      | 1523201196 |  Tom
 24    | 24      |  not good                | 1523208390 |  Lucas
 25    | 24      |  not good??              | 1523718726 |  Stephen
 26    | 24      |  why u said not good?    | 1523718805 |  Stephen
 27    | 24      |  tell me why u said?     | 1523718886 |  Stephen

我想要的是什么:

ut_id  | put_id  |        cm_tx             | da         |   un
 ------|---------|--------------------------|------------|--------
 21    | 21      |  was good                | 1523190974 |  Jonah
 22    | 21      |  thx                     | 1523197793 |  Sara
 23    | 23      |  that was good post      | 1523201196 |  Tom
 24    | 24      |  not good                | 1523208390 |  Lucas
 27    | 24      |  tell me why u said?     | 1523718886 |  Stephen
 26    | 24      |  why u said not good?    | 1523718805 |  Stephen
 25    | 24      |  not good??              | 1523718726 |  Stephen
  

(事实上,我想排序唯一的" ut_id!= put_id")ORDER BY da AND put_id

提前致谢

1 个答案:

答案 0 :(得分:2)

正如我从你想要的输出中理解的那样,你想要按put_id排序,然后按ut_id = put_id排序,然后按日期降序排序。你可以通过以下方式实现这一目标:

SELECT put_id,ut_id,cm_tx,date,un FROM TA ORDER BY put_id ASC, IF(ut_id = put_id, 0, 1) ASC, date DESC 

输出:

put_id ut_id   cm_tx                 date           un  
21     21      was good              1523190974     Jonah
21     22      thx                   1523197793     Sara
23     23      that was good post    1523201196     Tom
24     24      not good              1523208390     Lucas
24     27      tell me why u said?   1523718886     Stephen
24     26      why u said not good?  1523718805     Stephen
24     25      not good??            1523718726     Stephen