在一个查询中按不同标准选择几个随机行

时间:2013-10-08 08:13:43

标签: mysql random

我想从level = 1的表中选择4个随机行,并从同一个表中选择4个随机行,其中level = 2。我如何在1个查询中执行此操作?

2 个答案:

答案 0 :(得分:5)

select * from (select * from your_table 
               where level = 1 order by rand() limit 4) x
union all
select * from (select * from your_table 
               where level = 2 order by rand() limit 4) y

答案 1 :(得分:0)

尝试这样......

SELECT product_id, title, description FROM products WHERE active = 1 AND stock > 0 ORDER BY RAND() LIMIT 4;