Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Performance 兰德公司的业绩()_Performance_Random - Fatal编程技术网

Performance 兰德公司的业绩()

Performance 兰德公司的业绩(),performance,random,Performance,Random,我听说我应该避免使用“order by rand()”,但我确实需要使用它。与我所听到的不同,下面的问题出现得非常快 select cp1.img_id as left_id, cp1.img_filename as left_filename, cp1.facebook_name as left_facebook_name, cp2.img_id as right_id, cp2.img_filename as right_filename,

我听说我应该避免使用“order by rand()”,但我确实需要使用它。与我所听到的不同,下面的问题出现得非常快

select 

    cp1.img_id as left_id,
    cp1.img_filename as left_filename,
    cp1.facebook_name as left_facebook_name,
    cp2.img_id as right_id, 
    cp2.img_filename as right_filename,
    cp2.facebook_name as right_facebook_name    

from 
challenge_photos as cp1
cross join 
challenge_photos as cp2
where
(cp1.img_id < cp2.img_id) 
and 
(cp1.img_id,cp2.img_id) not in ((0,0)) 
and 
(cp1.img_status = 1 and cp2.img_status = 1) 
order by rand() limit 1
选择
cp1.img_id作为左_id,
cp1.img_文件名作为左_文件名,
cp1.facebook\u name作为左facebook\u name,
cp2.img_id作为右id,
cp2.img_文件名作为右_文件名,
cp2.facebook\u name作为右\u facebook\u name
从…起
挑战_照片为cp1
交叉连接
挑战_照片为cp2
哪里
(cp1.img_id

此查询是否被视为“正常”?或者我应该使用通过搜索“alternative to rand()”可以找到的查询吗?

这通常是一个性能问题。您应该尽可能避免使用每行函数,因为它们会降低查询速度

这意味着像
大写(名称)
薪水*1.1
等等。它还包括
rand()
。这可能不是一个直接的问题(10000行),但是,如果您想要扩展数据库,您应该记住这一点

两个主要问题是,您正在执行每行函数,然后必须在选择第一行之前对输出进行完整排序。如果按随机值排序,DBMS将无法使用索引

但是,如果你需要这样做(我不是在做判断),那么你需要这样做。在现实世界中,实用主义常常战胜教条主义:-)


若性能成为一个问题,一种可能性是通过以下方式获得记录计数:

select count(*) from ...
然后在客户端选择一个随机值并使用:

limit <start>, <count>
限制,

子句中,根据特定DBMS使用的语法进行调整。这将消除排序问题和通过网络传输不需要的数据。

很抱歉,我不知道您问题的具体答案,但这里有一些信息您可能知道,也可能不知道:为什么
ORDER BY RAND()不鼓励使用
,因为这样的查询要求SQL server为结果集中的每一行生成一个随机数(不考虑限制),并对多少条记录只进行最小的“非常快”排序?100? 10万?Alex Brault//是的,我是这么想的,但我有点困惑,因为查询速度非常快。@David Gelhar//现在,10万…请参阅以获得一些替代方案。