按组排序和逆序?

时间:2014-12-14 17:27:59

标签: mysql sql

我想根据每个名称的id的最大值按降序对表进行排序,但每个名称行的行应按升序排序。

我已经按照id。

对表格进行了排序
id  | name | other cloumns
----|------|---------------
11  | yv   |
10  | abc  |
9   | abc  |
8   | zx   |
7   | tv   |
6   | tv   |
5   | tv   |
4   | yv   |
3   | yv   |

我希望将其排序为

id  | name | other cloumns
----|------|---------------
3   | yv   | /*yv is on top because it had max id i.e. 11*/
4   | yv   |
11  | yv   |
9   | abc  | /*abc is second because it has 10*/
10  | abc  |
8   | zx   | /*zx is third because it has 8*/
5   | tv   | /*tv is fourth because it has 7*/
6   | tv   |
7   | tv   |

我该怎么做?我正在使用MySQL

3 个答案:

答案 0 :(得分:2)

你想:

order by name desc, id asc

您可以将多个密钥放入order by。第一个键用于排序。当键值相同时,第二个使用,依此类推。

编辑:

我知道,你首先需要id最小的名字。为此,请使用join

select t.*
from table t join
     (select name, max(id) as maxid
      from table t
      group by name
     ) n
     on t.name = n.name
order by n.maxid, t.name, t.id

答案 1 :(得分:1)

您可以将按订单联盟结合使用,如下所示:

select * from (select * from table1 order by id where name='yv')
  union all
select * from (select * from table1 order by id where name='abc')
  union all
select * from (select * from table1 order by id where name='zx')
  union all
select * from (select * from table1 order by id where name='tv')

修改

select tt.id,tt.name from 
(select max(t.id) tid,t.name from table1 t group by t.name order by tid desc) tb 
join (select * from table1 tb1 order by tb1.id) tt
on tb.name=tt.name

答案 2 :(得分:1)

这似乎提供了所要求的:

SELECT sampleData.id, sampleData.name
FROM
  sampleData
JOIN
    (
      SELECT
        @rowNum := @rowNum + 1 rowNumber
        , name
        , MAX(sampleData.id)
      FROM    sampleData, (SELECT @rowNum := 0) s
      GROUP BY name
      ORDER BY MAX(sampleData.id)
    ) orderedName
  ON sampleData.name = orderedName.name
ORDER BY orderedName.rowNumber, sampleData.id;

SQL Fiddle