MySQL选择order by的随机行

时间:2013-01-14 09:57:42

标签: mysql random sql-order-by

我想从表中检索随机行,但这些行必须按类别排序。

select category, 
   (select order_number 
   from orders 
   where order_number in (123,125,128,129,256,263,966,258,264,159,786) 
   order by rand()) 
from orders 
order by category

这是我试过的查询。但是,它会检索表中的整个数据。


工作查询;

SELECT category,order_number FROM (
    SELECT category,order_number 
    from orders 
    where order_number in (`$order_numbers_variable`) 
    order by rand()
) order by category

1 个答案:

答案 0 :(得分:1)

我认为要求是: 从“类别”排序的表格中检索“N”个随机行。

假设 N 10 。如果要更改行数,请在LIMIT子句中更改它。

SELECT * FROM (
    SELECT category from orders ORDER BY rand() ASC  LIMIT 10
) AS innerResult 
ORDER BY innerResult.category