简体   繁体   English

帮我优化随机记录查询

[英]Help me optimize a query for random records

I currently have a query for random records that's mad inefficient because it's ordering by RAND() and creating a temporary table each time it's called. 我目前正在查询一个效率极低的随机记录,因为它是由RAND()排序并在每次调用时创建一个临时表。 Also, this means that it cannot be cached. 同样,这意味着它不能被缓存。 It is also joined to another table which adds processing time and complicates things a little. 它还连接到另一个表,这增加了处理时间并使事情变得有些复杂。 So, help me optimize the following: 因此,请帮助我优化以下内容:

SELECT     listings.id, listings.price, listings.seller_id, sellers.blacklisted
FROM       listings
INNER JOIN sellers ON sellers.id = listings.sellers_id
WHERE      listings.price > 100
AND        sellers.blacklisted = 0
ORDER BY   RAND()
LIMIT 4

One way to start going about this is to run one query that returns a COUNT() of the possible listings, then a second query (or 4 others if it's to be truly random) with an offset set within RAND()*COUNT. 开始此操作的一种方法是运行一个查询,该查询返回COUNT()个可能的列表,然后运行第二个查询(如果真正是随机的,则返回4个),并在RAND()* COUNT中设置偏移量。

How would you approach this? 您将如何处理?

Assuming that listings is indexed on id: 假设listings在ID上建立索引:

If your id is an integer: 如果您的ID是整数:

SELECT     listings.id, listings.price, listings.seller_id, sellers.blacklisted
FROM       listings
INNER JOIN sellers ON sellers.id = listings.sellers_id
WHERE      listings.price > 100
AND        sellers.blacklisted = 0
AND        listings.ID LIKE CONCAT(CEIL(RAND() * 100),'%')
LIMIT 4

and if it's ascii 如果是ascii

SELECT     listings.id, listings.price, listings.seller_id, sellers.blacklisted
FROM       listings
INNER JOIN sellers ON sellers.id = listings.sellers_id
WHERE      listings.price > 100
AND        sellers.blacklisted = 0
AND        listings.ID LIKE CONCAT(CHAR(CEIL(RAND() * 100)),'%')
LIMIT 4

basically my advice to speed things up is dump the order by. 基本上我提速的建议是转储订单。 On anything over a few records you're adding measurable overhead. 在超过几条记录的任何内容上,您都在增加可衡量的开销。

ps please forgive me if concat can't be used this way in mqsql; ps如果无法在mqsql中使用concat,请原谅我; not entirely certain whether it'll work. 尚不确定是否会奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM