MySQL将选择查询随机化1个字段

时间:2014-11-21 01:42:15

标签: mysql sql-order-by

我有表 my_table

id  type  info
1    1    car
2    1    bicycle
3    1    train
4    2    ketchup
5    2    mustard
6    2    soda
7    3    flower
8    3    tree
9    3    grass

我需要进行选择查询,按类型对数据进行排序,以便结果像

一样
type info
1    car
2    ketchup
3    flower

1    bicycle
2    mustard
3    tree

1    train
2    soda
3    grass

现在

SELECT * from my_table ORDER BY type ASC

按类型111 222 333订购,我需要输入123 123 123。

1 个答案:

答案 0 :(得分:2)

MySQL没有窗口函数,因此这比其他数据库更难。

SELECT type, info
FROM (
    SELECT @rank := IF(type=@type, @rank+1, 1) AS rank, @type:=type AS type, info
    FROM (SELECT @rank:=0, @type:=null) _init, my_table
    ORDER BY type, id
) t
ORDER BY rank, type;

SQL Fiddle