目前,我有使用rand()命令进行查询以获取1000个不同的行而不递增的方法。
任何想法如何优化返回1000个随机结果而不递增的查询,例如:
select *
from table1
where not exists
( select id
from table2
where id = table1.id)
and prize_list_id = 100
and prize_group_id in (109,111,113,119,120,127,129)
order
by rand() limit 1000;
答案 0 :(得分:0)
大概,您不知道将返回多少行,因此需要计算。
想法如下:
rand()
子句中使用WHERE
将集合缩减为合理的数字。order by rand()
来获得最终的随机性。这看起来像:
select t.*
from (select t1.*, (@cnt := @cnt + 1) as seqnum,
rand() as rnd
from table1 t1 cross join
(select @cnt := 0) params
where not exists (select id
from table2
where id = table1.id
) and
prize_list_id = 100 and
prize_group_id in (109, 111, 113, 119, 120, 127, 129)
) t
where rnd < 2000 / @cnt
order by rnd
limit 1000
where
应该选择大约2000行,这是一个安全的数字,可以确保您至少有1000行(实际上,您可以使用较小的数字,例如1200)。 order by
然后位于较小的子集中,并且应该更快。
我不认为rand()
是一个特别昂贵的函数,但这会为每行预先计算一个值,因此在子查询中每行只调用一次。