简体   繁体   中英

How can I make this mysql query faster? Is the order a killer? The limit?

SELECT *  FROM table WHERE city LIKE example ORDER by RAND() Limit 10

I'm trying to return, obv, some random entries from a table, but it's on quite a few pages that get hit so it can cause the site to slow down. I comment out the query and all is well again so I know it's this, but I'd like to take this opportunity to learn a bit about how to do queries better.

I thought an index might help, but where there's no joins that seems unhelpful in this case. Thanks.

You can make this faster by adding an index on table(city) .

I think the query would be clearer using = rather than like :

SELECT t.* 
FROM table t
WHERE t.city = example
ORDER by RAND()
Limit 10;

Depending on how many rows are returned, there might be further optimizations.

For instance, one method is:

SELECT t.* 
FROM (SELECT t.*, RAND() as rnd, (@rn := @rn + 1) as rn
      FROM table t CROSS JOIN
           (SELECT @rn := 0) params
      WHERE t.city = example
     ) t 
WHERE rnd < (100 / @rn)  -- get a sample of about 100 records
ORDER BY rnd
LIMIT 10;

This uses variables and the WHERE to limit the rows to about 100 before sorting. That sort should be pretty fast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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