如何使用mysql随机排序结果?

时间:2015-12-13 13:48:54

标签: mysql sql

我有一张这样的表:

// mytable
+----+-------+-------+
| id | color | numb  |
+----+-------+-------+
| 1  | red   | 1     |
| 2  | red   | 2     |
| 3  | red   | 3     |
| 4  | blue  | 1     |
| 5  | blue  | 2     |
| 6  | green | 1     |
| 7  | green | 2     |
| 8  | green | 3     |
| 9  | green | 4     |
+----+-------+-------+

现在我希望随机(动态订单)为每个请求订购不同的订单。例如,这里是查询

select * from mytable where color = 'green' order by {?};

首次执行:

// newtable
+----+-------+-------+
| 7  | green | 2     |
| 6  | green | 1     |
| 8  | green | 3     |
| 9  | green | 4     |
+----+-------+-------+

第二次执行:

// newtable
+----+-------+-------+
| 9  | green | 4     |
| 8  | green | 3     |
| 6  | green | 1     |
| 7  | green | 2     |
+----+-------+-------+

等等......,没有任何具体的规则......只是随机的。那么,有没有任何mysql函数或任何方法呢?

2 个答案:

答案 0 :(得分:3)

您可以使用order by rand()rand()函数生成一个随机值,并记录在案here

答案 1 :(得分:0)

您可以尝试以下操作:

     SELECT * FROM mytable
     WHERE color = 'green'
     ORDER BY NEWID()

编辑:

     ORDER BY RAND()

也有效