随机子排序记录

时间:2012-02-18 11:43:48

标签: mysql random cycle

鉴于此示例性关系和数据

|_id_____|_type____|_name________|_date_______________|
| 1      | 1       | ajshdf      | 2012-02-18 12:35:00
| 2      | 1       | jkhae       | 2012-02-18 12:35:00
| 3      | 1       | dsfad       | 2012-02-18 12:35:00
| 4      | 2       | 3f3ad       | 2012-02-18 12:35:00
| 5      | 2       | gad64       | 2012-02-18 12:35:00
| 6      | 2       | as3da       | 2012-02-18 12:35:00
| 7      | 3       | faf3a       | 2012-02-18 12:35:00
| 8      | 3       | ga3d3       | 2012-02-18 12:35:00
| 9      | 4       | jzd64       | 2012-02-18 12:35:00

实现结果集的最佳方法是什么,它将尽可能均匀地分配记录,按类型排序?

我想要的是结果记录的排序方式是最新的条目始终位于顶部,但是类型会被改变,所以结果看起来像这样:

|_id_____|_type____|_name________|_date_______________|
| 1      | 1       | ajshdf      | 2012-02-18 12:35:00
| 4      | 2       | 3f3ad       | 2012-02-18 12:35:00
| 7      | 3       | faf3a       | 2012-02-18 12:35:00
| 9      | 4       | jzd64       | 2012-02-18 12:35:00
| 2      | 1       | jkhae       | 2012-02-18 12:35:00
| 5      | 2       | gad64       | 2012-02-18 12:35:00
| 8      | 3       | ga3d3       | 2012-02-18 12:35:00
| 3      | 1       | dsfad       | 2012-02-18 12:35:00
| 6      | 2       | as3da       | 2012-02-18 12:35:00
| 7      | 3       | faf3a       | 2012-02-18 12:35:00 

如你所见,type被改变并在结果中循环 - 1,2,3,4,1,2,3,1,2,3

1 个答案:

答案 0 :(得分:0)

效率很低但我觉得它会起作用:

SELECT a.*
FROM 
       TableX AS a
   JOIN 
       TableX AS b
     ON  b.type = a.type
     AND b.id <= a.id 
GROUP BY 
      a.id
ORDER BY
      COUNT(*)
    , a.id