RAND() Query and Performance

你说的曾经没有我的故事 提交于 2019-12-13 06:43:38

问题


I'm trying to prepare a query for performance. I'm hoping to remove the RAND() from the query below and replace it with a better performing alternative. Does anybody have any suggestions?

SELECT video.*, 
       video.wins / video.loses AS win_loss_ratio
  FROM video
 WHERE video.videoid NOT IN (SELECT vidlog.videoid
                               FROM video AS vid, 
                                    video_log AS vidlog
                              WHERE vid.videoid = vidlog.videoid)
   AND video.round = 0
ORDER BY RAND(), win_loss_ratio DESC 
LIMIT 0, 2

Thanks!


回答1:


Instead of using the RAND() use a random number in the offset for the LIMIT in the language that is calling this query. That could have two problems though a. you need to know how many items are in the database, 2. only yield something random for one of the items though. Other option is to drop the LIMIT and RAND() altogether and just select random items when the query is returned (I would imagine this to be slower though)

Is there a real reason why you need to have this very high in performance? I'm pretty sure using RAND() will be sufficient enough for this kind of query.




回答2:


Instead of the in subquery, try an exclusive left join? That way, MySQL knows it doesn't have to scan the video table twice:

SELECT  video.* 
,       video.wins / video.loses AS win_loss_ratio
FROM    video
LEFT JOIN    
        video_log as vidlog
ON      vid.videoid = vidlog.videoid
WHERE   vidlog.videoid is null
        AND video.round =0
ORDER BY 
        RAND()
LIMIT   0 , 2


来源:https://stackoverflow.com/questions/5445055/rand-query-and-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!