In what order does Rails execute database queries

In Randomly select n objects with a condition in Rails . Anurag kindly suggested this answer for randomly selecting n posts with votes> = x

Post.all(:conditions => ["votes >= ?", x], :order => "rand()", :limit => n) 

my concern is that the number of posts with more than x votes is very large.

What is the order in which the database applies this criterion to the query?

it

  • (a) select n posts with votes> x, and then rank them? or
  • (b) select all messages with votes> x, and then rank and then select the n first messages?
  • (c) another?
+1
source share
3 answers

The development log check recommendation is very helpful.

However, in this case, randomization occurs at the end of MySQL, and not inside Active Record. To see how the query is executed in MySQL, you can copy the query from the log and paste it into your choice of MySQL (console, graphical interface, etc.) and add "EXPLAIN" to it.

You should get something like:

 EXPLAIN SELECT * FROM posts WHERE votes >= 'x' ORDER BY rand() LIMIT n 

When I try to execute a similar query in MySQL, they tell me:

 Select Type: SIMPLE Using where; Using temporary; Using filesort 

Then you need to search for great SO tips on how to optimize MySQL queries. If a problem occurs, adding an index to the vote column can improve performance. situation.

+3
source

As Toby has already pointed out, this is purely up to the SQL server, everything is done in the query itself.

However, I am afraid that you will not be able to get a truly randomized result if the database does not first receive the entire result set and then randomizes it. Although, in any case, you should check the EXPLAIN result.

+1
source

See development.log for the generated request should give you a key.

0
source

Source: https://habr.com/ru/post/1299850/


All Articles