通过查询mysql高级顺序

时间:2015-07-09 17:10:42

标签: mysql sql

我在MySQL中有这样的表:

+-----+------+
| id  | type |
+-----+------+
| 149 |    8 |
| 150 |    7 |
| 151 |    8 |
| 152 |    7 |
| 153 |    5 |
| 154 |    6 |
| 155 |    3 |
| 156 |    2 |
| 157 |    4 |
| 158 |    2 |
| 159 |    1 |
| 160 |    0 |
+-----+------+

我想对此表进行排序,并收到如下结果:

+-----+------+
| id  | type |
+-----+------+
| 151 |    8 |
| 152 |    7 |
| 154 |    6 |
| 153 |    5 |
| 157 |    4 |
| 155 |    3 |
| 158 |    2 |
| 159 |    1 |
| 160 |    0 |
| 149 |    8 |
| 150 |    7 |
| 156 |    2 |
+-----+------+

作为进一步的解释,我想对类型列进行排序,例如继续倒计时:8,7,6,5,4,3,2,1,0,8,7,6,5,4,3,2,1,0,8,7,...

是否有可能对这样的表进行排序?或通过程序或其他方式实现该结果?

3 个答案:

答案 0 :(得分:4)

 SELECT id, TYPE FROM (
   SELECT id, TYPE, 
   IF(@myvar = 0 OR @myvar = TYPE, @counter := @counter + 1, @counter := 1) sequence,  
   @myvar := TYPE FROM mytable 
   JOIN (SELECT @myvar := 0, @counter := 0 ) a
   ORDER BY TYPE DESC, id) b 
ORDER BY sequence, TYPE DESC,  id

此查询适用于任何级别。

如有必要,请设置外部查询以仅提取相关字段。

结帐SqlFiddle

答案 1 :(得分:0)

仅当类型的频率为 2 时才会有效。

在程序中编写以下代码:

drop temporary table if exists tmp;
create temporary table tmp
select min(id) as min_id ,max(id) as max_id from  table_name group by type;

select * from table_name where id in( select max_id from tmp) order by type
union all
select * from table_name where id in(select min_id from tmp) order by type;

答案 2 :(得分:0)

尝试此查询

select id,type from(
SELECT a.id, a.Type, count(*) as row_number FROM test a
JOIN test b ON a.type = b.type AND a.id >= b.id
GROUP BY a.Type, a.id) a
order by row_number