Taking n random elements from a table with a constraint
I'm trying to select a random n elements from a table with the constraint that the category_id = 0 (where category_id = 0). Before, I used probabilistic stream sampling to do so because it doesn't scan every element.
However, is there a way to do this with the extra where constraint?
It doesn't make sense to pull out all the elements and then select a random n elements because the table is millions of rows.
My previous query without the extra constraint is pasted below.
SELECT *
FROM (SELECT @cnt := COUNT(*) + 1, @lim := %s
FROM table) vars
STRAIGHT_JOIN (SELECT *,
@lim := @lim-1
FROM table
WHERE (@cn开发者_Python百科t := @cnt - 1) AND RAND() < @lim / @cnt) drv_tbl
Try this,
select * from <table> where <constrain> order by RAND() limit 0,<n>
精彩评论